Categories
Uncategorized

SpringMVC three kinds of exception handling mode

SpringMVC three kinds of exception handling mode

In SpringMVC, SpringBoot processing web requests, or an exception if an error is encountered, returned to the user a good error message better than Whitelabel Error Page. SpringMVC provides three exception handling, the use of which can provide good error-readable message to the user.

1. To achieve HandlerExceptionResolver

public class AppHandlerExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("message", ex.getMessage());
        // 可以设置视图名导向错误页面
        mav.setViewName("/error");
        // 直接返回视图
        // 如果返回 null,则会调用下一个 HandlerExceptionResolver
        return mav;
    }
}

And then configure a HandlerExceptionResolver

@Bean
public AppHandlerExceptionResolver appHandlerExceptionResolver() {
    return new AppHandlerExceptionResolver();
}

HandlerExceptionResolver implementation class will catch an abnormal condition when @Controller method performed, the processing returns as a result of post-ModelAndView view, and therefore can be custom exception view through it.

HandlerExceptionResolver @Controller layer can only catch exceptions that occur (including @Controller @Service call exception occurs), the rest of abnormalities, such as access to a path that does not exist, will not be captured HandlerExceptionResolver, this time will jump ErrorController treatment, Here we will discuss.

2. @ControllerAdvice and @ExceptionHandler comment

// 可以配置拦截指定的类或者包等
// @RestControllerAdvice 使 @ExceptionHandler 注解的方法默认具有 @ResponseBody 注解
@RestControllerAdvice(basePackageClasses = HelloWorldController.class)
public class AppExceptionHandlerAdvice {

    // 配置拦截的错误类型
    // 这里也可以返回 ModelAndView 导向错误视图
    @ExceptionHandler(Exception.class)
    public ResponseEntity responseEntity(Exception e) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        Map map = new HashMap<>();
        map.put("status", 400);
        map.put("message", e.getMessage());
        // 直接返回结果
        return new ResponseEntity<>(map, headers, HttpStatus.BAD_REQUEST);

    }
}

Exception processing configuration achieved in this way is processed by the default class HandlerExceptionResolverComposite HandlerExceptionResolver therefore can only catch exceptions @Controller layer.

@ExceptionHandler can return ModelAndView custom exception view.

@ControllerAdvice can intercept specific classes, @ ExceptionHandler can intercept specific exceptions, the configuration can be more precise exception handling logic.

@ExceptionHandler @Controller can be declared in the class, this time can only handle exceptions of the same class

3. Custom ErrorController bean

@RestController
@RequestMapping("/error")
public class AppErrorController extends AbstractErrorController {

    public AppErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping
    public ResponseEntity> error(HttpServletRequest request) {
        Map body = getErrorAttributes(request, false);
        HttpStatus status = getStatus(request);
        // 返回响应体
        return new ResponseEntity<>(body, status);
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

If no ErrorController, SpringBoot automatically configured by a ErrorMvcAutoConfiguration, the default implementation class is BasicErrorController.

ErrorController can handle exceptions thrown by [email protected] layer, such as a common access path that does not exist.

ErrorController can be unified error handling, that let ModelAndView guide HandlerExceptionResolver returned an error page.

Leave a Reply