400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

总结Spring异常处理

这篇文章主要为大家展示了总结Spring异常处理,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。

创新互联于2013年开始,先为卫辉等服务建站,卫辉等地企业,进行企业商务咨询服务。为卫辉企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

1. 前言

统一的异常处理对于应用的重要性不言而喻。今天我们来介绍一下 Spring如何来进行统一的 Rest异常处理。同时我们也会简单比较一下它们之间的优劣。

2. @Controller 结合 @ExceptionHandler

在控制器中声明一个方法然后用 @ExceptionHandler 注解标记即可:

 @Controller
 @RequestMapping("/test")
 public class TestController {
 
   @RequestMapping("/err")
   @ResponseBody
   public Object demo1(){
     int i = 1 / 0;
     return new Date();
   }
 
   @ExceptionHandler({RuntimeException.class})
   public ModelAndView fix(Exception ex){
     System.out.println(ex.getMessage());
     return new ModelAndView("error",new ModelMap("ex",ex.getMessage()));
   }
 }

优点:

缺点:

3. @ControllerAdvice 结合 @ExceptionHandler

这是 2.的改进型,通过定义 @ControllerAdvice 类并在方法上标记 @ExceptionHandler ,达到了全局异常处理的目的:

 @ControllerAdvice
 public class TestController {
 
 
   @ExceptionHandler({RuntimeException.class})
   public ModelAndView fix(Exception ex){
     System.out.println(ex.getMessage());
     return new ModelAndView("error",new ModelMap("ex",ex.getMessage()));
   }
 }

优点:

缺点:

一般情况下也建议使用该方式进行异常处理。大多数情况下都是兼容的。

4. HandlerExceptionResolver 接口

实现 HandlerExceptionResolver 接口,这里我们继承其抽象实现 AbstractHandlerExceptionResolver :

 @Component
 public class RestResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver {
 
   @Override
   protected ModelAndView doResolveException(
    HttpServletRequest request, 
    HttpServletResponse response, 
    Object handler, 
    Exception ex) {
     try {
       if (ex instanceof IllegalArgumentException) {
         return handleIllegalArgument((IllegalArgumentException) ex, response, handler);
       }
      //todo more exception
     } catch (Exception handlerException) {
        //todo 
     }
     return null;
   }
 
   private ModelAndView 
    handleIllegalArgument(IllegalArgumentException ex, HttpServletResponse response) 
    throws IOException {
     response.sendError(HttpServletResponse.SC_CONFLICT);
     String accept = request.getHeader(HttpHeaders.ACCEPT);
      //todo more response
     return new ModelAndView();
   }
 }

优点:

缺点:

5. Spring Boot 中的异常处理

如果你用的框架是 Spring Boot。 我们还可以用它独特的处理方式。优点是屏蔽了低级的API,缺点也比较明显,无法捕捉到具体的异常。

5.1 实现 ErrorController

Spring Boot在默认情况下,提供了 /error 映射来处理所有错误,在 Servlet容器里注册了全局的错误页面(Whitelabel Error Page)并返回客户端。
通过实现 ErrorController接口并注册为 Bean。这里不再举例。可参考 BasicErrorController

5.2 添加 ErrorAttributes

我们也可以添加 ErrorAttributes类型的 Bean来替换替换默认的异常处理。

 @Component
 public class MyCustomErrorAttributes extends DefaultErrorAttributes {
 
   @Override
   public Map getErrorAttributes(
    WebRequest webRequest, boolean includeStackTrace) {
     Map errorAttributes = 
      super.getErrorAttributes(webRequest, includeStackTrace);
     errorAttributes.put("locale", webRequest.getLocale()
       .toString());
     errorAttributes.remove("error");
 
     //todo your business
 
     return errorAttributes;
   }
 }

5.3 继承基类 BasicErrorController

Spring Boot自动配置还提供了实现 ErrorController接口异常处理的基类 BasicErrorController,默认是处理 text/html类型请求的错误,可以继承该基类自定义处理更多的请求类型,添加公共方法并使用 @RequestMapping注解的 produce属性指定处理类型。

 @Component
 public class MyErrorController extends BasicErrorController {
 
   public MyErrorController(ErrorAttributes errorAttributes) {
     super(errorAttributes, new ErrorProperties());
   }
 
   @RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)
   public ResponseEntity> xmlError(HttpServletRequest request) {
     
   //todo your business
 
   }
 }

6. Spring 5 的 ResponseStatusException

另外在最新的 Spring 5中你还可以通过 抛出 ResponseStatusException 异常来进行处理。

好处:

缺点:

以上就是关于总结Spring异常处理的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。


文章标题:总结Spring异常处理
网站路径:http://mbwzsj.com/article/ighgde.html

其他资讯

让你的专属顾问为你服务