本文主要是介绍spring使用@ExceptionHandler、@ControllerAdvice统一异常处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. 自己定义的异常,继承RuntimeException。可以建个exception包,专门放自定义异常。自定义的异常用来描述自己程序中特有的异常。
public class CustomGenericException extends RuntimeException {
private String errCode;
private String errMsg;
public CustomGenericException(String errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
public String getErrCode() {
return errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
}
2. 定义一个专用做处理异常的类,如下, @ExceptionHandler()括号中的异常类.class表示这个方法用来处理哪种异常。
@ControllerAdvice(annotations = Controller.class)
public class GlobalExceptionController {
@ExceptionHandler(CustomGenericException.class)
public ModelAndView handleCustomerException(CustomGenericException ex) {
ModelAndView model = new ModelAndView("error/generic_error");
model.addObject("errCode", ex.getErrCode());
model.addObject("errMsg", ex.getErrMsg());
return model;
}
@ExceptionHandler(Exception.class)
public ModelAndView handleAllException(Exception ex) {
ModelAndView model = new ModelAndView("error/generic_error");
model.addObject("errMsg", "this is Exception.class");
return model;
}
}
3. 程序中只管抛异常就可以, 可以抛自定义的异常,或其他异常,异常处理类中对应的异常处理办法会起作用。
@Controller
public class MainController {
@RequestMapping(value = "/{type}", method = RequestMethod.GET)
public ModelAndView getPages(@PathVariable("type") String type) throws IOException {
if("error".equals(type)) {
throw new CustomGenericException("E888", "This is custom message");
} else if("io-error".equals(type)) {
throw new IOException();
} else {
return new ModelAndView("index").addObject("msg", type);
}
}
4. spring配置文件中要能扫到这些bean, 并且加上<mvc:annotation-driven/>
<context:component-scan base-package="com.***">
</context:component-scan>
<mvc:annotation-driven/>
这篇关于spring使用@ExceptionHandler、@ControllerAdvice统一异常处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!