1、使用
ControllerAdvice
@ControllerAdvice
@RestController
public class AppWideExceptionHandler {
@ExceptionHandler({MissingPathVariableException.class, MissingServletRequestParameterException.class, NullPointerException.class, BindException.class, NoHandlerFoundException.class, MethodArgumentNotValidException.class, NoSuchRequestHandlingMethodException.class})
public Object handleException() {
return new Result("test", 404);
}
}
2、使用
HandlerExceptionResolver
class MyExceptionHandler implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("ex", ex);
// 根据不同错误转向不同页面
if(ex instanceof BusinessException) {
return new ModelAndView("business_error", model);
}else if(ex instanceof ParameterException) {
return new ModelAndView("parameter_error", model);
} else {
return new ModelAndView("error", model);
}
}
}
springmvc 统一异常处理
最新推荐文章于 2024-07-08 10:45:20 发布