「SpringMVC入門」例外をハンドリングする@ExceptionHandlerの書き方

1.内部exception(Controllerのみ)
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
ModelAndView mv = new ModelAndView(“error");
mv.addObject(“exception", ex);
System.out.println(“in testExceptionHandler");
return mv;
}

@RequestMapping(“/error")
public String error(){
int i = 7/0;
return “hello";
}

2.global exceprion(全てのController)
@ControllerAdvice
public class testControllerAdvice {
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
ModelAndView mv = new ModelAndView(“error");
mv.addObject(“exception", ex);
System.out.println(“in testControllerAdvice");
return mv;
}
}

3.設定ファイル
<!– configure SimpleMappingExceptionResolver –>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
</bean>

Software

Posted by arkgame