spring 公用异常处理
1. 采用spring boot注解方式,如果采用swagger的话会导致swagger不可用
1.1 spring 配置如下
#出现错误时, 直接抛出异常 spring.mvc.throw-exception-if-no-handler-found=true #不要为我们工程中的资源文件建立映射 spring.resources.add-mappings=false
如果设置为ture,当访问不存在的路径或入参解析异常等,会出现框架自定义异常即1.2的配置的异常信息,swagger出现404
如果设为false,swagger正常,其它异常会出现如下页面
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Jun 21 14:01:28 CST 2019
There was an unexpected error (type=Not Found, status=404).
No message available
1.2 增加公用异常拦截
ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) @ResponseBody public String defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { return "xxx"; } }
2. 如果要处理错误路径问题且要swagger可用,可以参考org.springframework.boot.autoconfigure.web.BasicErrorController重写自己的
@Controller @RequestMapping("${server.error.path:${error.path:/error}}") public class FundaErrorController implements ErrorController { private static final String PATH = "/error"; @Autowired private ErrorAttributes errorAttributes; @Override public String getErrorPath() { return PATH; } @RequestMapping @ResponseBody public String doHandleError(HttpServletRequest request) { return "xxxx"'; } }