SpringBoot自带的异常处理
SpringBoot有一个默认的视图“/error”来处理所有的异常,并且该视图注册成全局的错误页面在服务中,在客户端中他返回带有状态和错误码的json类型的响应。
取代默认的视图来处理
To replace the default behavior completely, you can implement ErrorController and register a bean definition of that type or add a bean of type ErrorAttributes to use the existing mechanism but replace the contents.
自定义带注解的类处理
You can also define a class annotated with @ControllerAdvice to customize the JSON document to return for a particular controller and/or exception type
自定义错误处理类来返回json格式的响应
1 | (basePackageClasses = AcmeController.class) |
- basePackageClasses: 标识限定控制器,可以去掉,以对所有控制器生效,会产生性能影响
- ExceptionHandler: 拦截自定义错误,可以去掉拦截所有错误类型
- handleControllerException: 在此方法中返回自定义的ResponseBody