spring boot exception (Exception) Processing


Spring Boot Integration Tutorial


Outline

Exception handling annotations

spring can handle exceptions 2 Notes:

  • @ControllerAdvice Globally, the controller handles all exceptions
  • @ExceptionHandler Local, only an exception for a controller

First there is ExceptionHandler, then there ControllerAdvice, ExceptionHandlercan not focus on exceptions, ControllerAdviceintroduced to compensate for this shortcoming, it is recommended to use ControllerAdvice. This article describes the ControllerAdviceusage of ExceptionHandlernot introduced, For refer to the relevant information.

Error Handling page: ErrorController

ErrorControllerThe role is set to servlet error page, the default error page is Whitelabel, to access a nonexistent page will display this error page.

image

Through inheritance ErrorControlleryou can set up a custom error page interface.

@RestController
public class MyErrorController implements ErrorController {
    
    @RequestMapping(value = "/error")
    public ResponseEntity<Result> error() {
        Result res = new Result(404, "页面未找到");
        return new ResponseEntity<Result>(res, HttpStatus.NOT_FOUND);
    }

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

If ControllerAdvicethere are no direct return http response, continue to throw an exception, it will be called ErrorControlleran error page. If the ControllerAdvicecapture and direct the abnormal returns http response, there is no need to configure ErrorControllererror pages in the.

404 Abnormal

spring boot default does not throw an exception 404 (NoHandlerFoundException), so in ControllerAdvicethe not catch the exception, resulting in 404 always skip ContollerAdvicedirectly display ErrorControllererror page. We need to change the configuration, so that 404 errors thrown (NoHandlerFoundException), so you can in ControllerAdvicecatch this exception. Change the configuration, in application.propertiesthe Add:

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

Abnormal filter

ContollerAdviceCan not capture filter thrown exception, require special treatment for such an exception.

The [spring boot rest interface integration spring security (2) - JWT Configuration] JWT filter section, the exception handling process required to provide a special class.

Use ContollerAdvicecan for centralized processing for all abnormality controllers, through a process described below the actual item.

Project Description

Simulate a registered user interfaces, throws an exception so that all types of ContollerAdvicetreatment.

Claim

  • JDK1.8 or later
  • Eclipse development environment

The development environment is not, refer to the previous section [spring boot development environment to build (Eclipse)].

Project Creation

Create a spring boot project

Open Eclipse, create spring starter project spring boot of the project, select the menu: File > New > Project ...pop-up dialog box, select: Spring Boot > Spring Starter Projectwhen configuring dependent, check web, complete the project creation.

image

Project Configuration

application.properties Configuration

## 服务器端口,默认是8080
server.port=8096 

## 让404错误抛出异常,需要同时设置spring.resources.add-mappings为false
#  让404错误抛出异常
spring.mvc.throw-exception-if-no-handler-found=true
# 禁用静态资源的自动映射,如不禁用,不存在的url将被映射到/**,servlet不有机会抛出异常
spring.resources.add-mappings=false

## log级别设置为debug, 通过log.debug打印异常信息
logging.level.root=DEBUG

If you use automatic mapping of static resources, there will be mapped to the url / **, servlet not have the opportunity to throw an exception. It did not deal with static resources in the rest api project, completely prohibited.

Code

Project directory structure as shown below, we've added a few classes, detailed below.

image

Exception class ErrorHandler.java

This class is to add ControllerAdviceexception handling class annotation, abnormal all controllers, are here to focus on. Here we achieved Class 2 special exception handler, and a default exception handler.

  • Check exception handling input parameters
  • 404 Exception Handling
  • The default exception handler, handle all other exceptions

@ControllerAdvice //表明这是控制器的异常处理类
public class ErrorHandler {
    
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(ErrorHandler.class);
    
    /**
     * 输入参数校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<Result> NotValidExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e) throws Exception {
        
        log.debug("异常详情", e);
        BindingResult bindingResult = e.getBindingResult();
        
        //rfc4918 - 11.2. 422: Unprocessable Entity          
        Result res = MiscUtil.getValidateError(bindingResult);
        return new ResponseEntity<Result>(res, HttpStatus.UNPROCESSABLE_ENTITY);
    }
    
    /**
     * 404异常处理
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ResponseEntity<Result> NoHandlerFoundExceptionHandler(HttpServletRequest req, Exception e) throws Exception {
        
        log.debug("异常详情", e);
                
        Result res = new Result(404, "页面不存在");
        return new ResponseEntity<Result>(res, HttpStatus.NOT_FOUND);
    }
    
    /**
     *  默认异常处理,前面未处理
     */
    @ExceptionHandler(value = Throwable.class)
    public ResponseEntity<Result> defaultHandler(HttpServletRequest req, Exception e) throws Exception {
                
        Result res = new Result(500, "服务器内部错误");
        log.debug("异常详情", e);
        
        return new ResponseEntity<Result>(res, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Check exception handling input parameters, [input data check spring boot (validation)] in the chapter, the controller is returned directly bindingResult, now unitary on here, the advantage is no longer necessary to write each interface of a repeating return bindingResultcode .

Controller AuthController

AuthControllerA simulated user interface implemented registered, return data validation bindingResultcode is removed, spring boot directly thrown MethodArgumentNotValidException, and then the ErrorHandleracquisition process.

@RestController
@RequestMapping("/auth")
public class AuthController {
    
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces="application/json")
    public ResponseEntity<Result> register(
        @Valid @RequestBody RegisterRequest register
//      , BindingResult bindingResult
    ) throws Exception {
        
//      if(bindingResult.hasErrors()) { 
//          
//          Result res1 = MiscUtil.getValidateError(bindingResult);
//          return new ResponseEntity<Result>(res1, HttpStatus.UNPROCESSABLE_ENTITY);
//      }
        
        Result res = new Result(200, "ok");
        return ResponseEntity.ok(res);
    }
}

RegisterRequest (DTO / data transfer object)

RegisterRequest class accepts and verifies the user registration information inputted. Tutorial on available data check [spring boot input data check (validation)].


public class RegisterRequest {
    
    @SuppressWarnings("unused")
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(RegisterRequest.class);
    
    @NotNull(message="手机号必须填")
    @Pattern(regexp = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$", message="账号请输入11位手机号") // 手机号
    private String mobile;
    
    @NotNull(message="昵称必须填")
    @Size(min=1, max=20, message="昵称1~20个字")
    private String nickname;
    
    @NotNull(message="密码必须填")
    @Size(min=6, max=16, message="密码6~16位")
    private String password;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
        
}

Auxiliary class

  • Wrapper Class Result Results
  • MiscUtil miscellaneous functions

run

Eclipse on the left, right click on the project root directory pop-up menu, choose: run as -> spring boot apprun the program. Open Postman access interface, results are as follows:

User registration, enter wrong information

image

Access a nonexistent URL

image

to sum up

The complete code

Guess you like

Origin www.cnblogs.com/jinbuqi/p/11038717.html