• Rest Error Handle


    解决方案1:控制器层次@ExceptionHandler

    public class FooController{
         
        //...
        @ExceptionHandler({ CustomException1.class, CustomException2.class })
        public void handleException() {
            //
        }
    }
    

    解决方案2:统一的The HandlerExceptionResolver

    1.ExceptionHandlerExceptionResolver
    2.DefaultHandlerExceptionResolver
    3.ResponseStatusExceptionResolver

    @ResponseStatus

    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public class MyResourceNotFoundException extends RuntimeException {
        public MyResourceNotFoundException() {
            super();
        }
        public MyResourceNotFoundException(String message, Throwable cause) {
            super(message, cause);
        }
        public MyResourceNotFoundException(String message) {
            super(message);
        }
        public MyResourceNotFoundException(Throwable cause) {
            super(cause);
        }
    }
    

    4.custom HandlerExceptionResolver

    @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);
                }
                ...
            } catch (Exception handlerException) {
                logger.warn("Handling of [" + ex.getClass().getName() + "] 
                  resulted in Exception", handlerException);
            }
            return null;
        }
     
        private ModelAndView 
          handleIllegalArgument(IllegalArgumentException ex, HttpServletResponse response) 
          throws IOException {
            response.sendError(HttpServletResponse.SC_CONFLICT);
            String accept = request.getHeader(HttpHeaders.ACCEPT);
            ...
            return new ModelAndView();
        }
    }
    

    解决方案3:@ControllerAdvice

    ControllerAdvice
    public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
        @ExceptionHandler(value 
          = { IllegalArgumentException.class, IllegalStateException.class })
        protected ResponseEntity<Object> handleConflict(
          RuntimeException ex, WebRequest request) {
            String bodyOfResponse = "This should be application specific";
            return handleExceptionInternal(ex, bodyOfResponse, 
              new HttpHeaders(), HttpStatus.CONFLICT, request);
        }
    }
    

    解决方案4:ResponseStatusException

    @GetMapping(value = "/{id}")
    public Foo findById(@PathVariable("id") Long id, HttpServletResponse response) {
        try {
            Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
     
            eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
            return resourceById;
         }
        catch (MyResourceNotFoundException exc) {
             throw new ResponseStatusException(
               HttpStatus.NOT_FOUND, "Foo Not Found", exc);
        }
    }
    

    解决方案5:customAccessDeniedHandler

    @Component
    public class CustomAccessDeniedHandler implements AccessDeniedHandler {
     
        @Override
        public void handle
          (HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) 
          throws IOException, ServletException {
            response.sendRedirect("/my-error-page");
        }
    }
    //configure
    @Component
    public class CustomAccessDeniedHandler implements AccessDeniedHandler {
     
        @Override
        public void handle
          (HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) 
          throws IOException, ServletException {
            response.sendRedirect("/my-error-page");
        }
    }
    //accessDeniedException
    @ControllerAdvice
    public class RestResponseEntityExceptionHandler 
      extends ResponseEntityExceptionHandler {
     
        @ExceptionHandler({ AccessDeniedException.class })
        public ResponseEntity<Object> handleAccessDeniedException(
          Exception ex, WebRequest request) {
            return new ResponseEntity<Object>(
              "Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN);
        }
         
        ...
    }
    

    解决方案6:ErrorController

    //custom ErrorController
    @Component
    public class MyCustomErrorAttributes extends DefaultErrorAttributes {
     
        @Override
        public Map<String, Object> getErrorAttributes(
          WebRequest webRequest, boolean includeStackTrace) {
            Map<String, Object> errorAttributes = 
              super.getErrorAttributes(webRequest, includeStackTrace);
            errorAttributes.put("locale", webRequest.getLocale()
                .toString());
            errorAttributes.remove("error");
     
            //...
     
            return errorAttributes;
        }
    }
    //BasitController
    @Component
    public class MyCustomErrorAttributes extends DefaultErrorAttributes {
     
        @Override
        public Map<String, Object> getErrorAttributes(
          WebRequest webRequest, boolean includeStackTrace) {
            Map<String, Object> errorAttributes = 
              super.getErrorAttributes(webRequest, includeStackTrace);
            errorAttributes.put("locale", webRequest.getLocale()
                .toString());
            errorAttributes.remove("error");
     
            //...
     
            return errorAttributes;
        }
    }
    
  • 相关阅读:
    基于IPV6的数据包分析
    OSPFv3与OSPF的配置
    防火墙技术综合实验
    基于服务器的AAA配置实验
    基于服务器的AAA实验
    ipv6到ipv4隧道6to4(GNS3)
    Intellij IDEA(idea) 设置创建文件自动添加创建人和创建时间
    虎扑盖饭系列的数据爬虫和分析
    优酷评论爬虫
    MySQL聚族索引、辅助索引、回表和索引覆盖
  • 原文地址:https://www.cnblogs.com/zhouyu0-0/p/12246777.html
Copyright © 2020-2023  润新知