全局异常处理
1、定义handler
@RestControllerAdvice
public
class SelfExceptionHandler {
/**
* 处理Exception
*
@return
*/
@ExceptionHandler(Exception.
class)
public
Result handleServiceException(Exception
e) {
e.printStackTrace();
return
new
Result(
e
);
}
}
2、写业务的地方抛出异常
throw new Exception("xxx");
自定义异常处理,其实就是自定义一个异常类,例如:BusinessException
然后替换掉handler里面对应的地方
@RestControllerAdvice
public
class SelfExceptionHandler {
/**
* 处理Exception
*
@param
e
*
@return
*/
@ExceptionHandler(
BusinessException.
class)
public
Result handleServiceException(
BusinessException
e) {
e.printStackTrace();
return
new
Result(
e
);
}
}
如果你想把处理结果渲染到页面,可以把
@RestControllerAdvice改成
@ControllerAdvice,
然后添加如下方法:
@ExceptionHandler(Exception.
class)
public ModelAndView handleServiceException(Exception
e) {
ModelAndView
modelAndView =
new ModelAndView();
modelAndView.setViewName(
"500");
modelAndView.addObject(
"code",
e.getMessage());
return
modelAndView;
}