Global exception handler (Global return processing is still required after completion)
When I first started to contact the project structure, I may have doubts about some of them. For example, I actually do
Rewriting ErrorController does not jump to the native error page, but throws our custom exception
Global exception handling refers to the unified and automatic handling of exceptions in the whole system. Programmers can handle exceptions in the project without some try/catch.
Why do you need global exception handling?
-
The first reason: there is no need to force to write try/catch. Exceptions are captured by a unified exception handling mechanism.
-
The second reason: custom exception: it can only be caught with global exception.
-
The third reason: the parameter verifier of JSR303 throws an exception if the parameter verification fails, and it cannot be captured directly through try/catch.
Encoding to realize the global exception configuration of springboot
Step 1: uniformly encapsulate exception handling enumeration classes
package com.kuangstudy.exception; import lombok.Getter; /** * @Author xuke * @Description Special exception handling * @Date 21:14 2021/6/25 * @Param * @return **/ @Getter public enum ResultCodeEnum { UNKNOWN_REASON(false, 20001, "unknown error"), SERVER_ERROR(false, 500, "The server is busy, please try again later"), ORDER_CREATE_FAIL(false, 601, "Order placing failed"); private Boolean success; private Integer code; private String message; private ResultCodeEnum(Boolean success, Integer code, String message) { this.success = success; this.code = code; this.message = message; } }
Step 2: encapsulate the exception result handling of the controller
package com.kuangstudy.exception; import com.kuangstudy.common.R; import lombok.*; @Builder @AllArgsConstructor @NoArgsConstructor @Data @ToString public class ErrorHandler { // ErrorHandler === R answer: do not want to destroy r class. // The status code of the exception, obtained from the enumeration private Integer status; // Exception message, write exceptions that users can understand, and get them from enumeration private String message; // Exception name private String exception; /** * Unified encapsulation of exception handling * * @param resultCodeEnum Exception enumeration * @param throwable An exception occurred * @param message Exception message null /by zero * @return */ public static ErrorHandler fail(ResultCodeEnum resultCodeEnum, Throwable throwable, String message) { ErrorHandler errorHandler = ErrorHandler.fail(resultCodeEnum, throwable); errorHandler.setMessage(message); return errorHandler; } /** * Encapsulate exception enumeration * * @param resultCodeEnum * @param throwable * @return */ public static ErrorHandler fail(ResultCodeEnum resultCodeEnum, Throwable throwable) { ErrorHandler errorHandler = new ErrorHandler(); errorHandler.setMessage(resultCodeEnum.getMessage()); errorHandler.setStatus(resultCodeEnum.getCode()); errorHandler.setException(throwable.getClass().getName()); return errorHandler; } }
Step 3: define a global exception handler
package com.kuangstudy.config.handler; import com.kuangstudy.common.base.ErrorHandler; import com.kuangstudy.common.base.ResultCodeEnum; import com.kuangstudy.config.exception.BusinessException; import com.kuangstudy.config.exception.OrderException; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; @RestControllerAdvice @Slf4j public class GlobalExceptionHandler { /** * Handle 500 exceptions on the server uniformly */ @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(Throwable.class) public ErrorHandler makeExcepton(Throwable e, HttpServletRequest request) { ErrorHandler errorHandler = ErrorHandler.fail(ResultCodeEnum.SERVER_ERROR, e); log.error("The requested address is:{},The exceptions are:{}", request.getRequestURL(), e); return errorHandler; } }
- The makeexception method is used to encapsulate runtime exceptions as ErrorHandler objects for unified capture and processing.
- @RestControllerAdvice and @ ControllerAdvice are enhanced extension processing for controller, and global exception is one of the extension capabilities.
- @ExceptionHandler(Throwable.class): handle certain types of exceptions in a unified way, so as to reduce the complexity and repetition rate of exceptions in the code,
- @Responsestatus (httpstatus. International_server_error): Specifies the http status code received by the client. If 500 is configured here, it will be displayed as 500 error. It's OK not to specify. Because the return is processed according to its own enumeration.
Step 4: define the test class
package com.kuangstudy.controller; import com.kuangstudy.entity.User; import io.swagger.annotations.Api; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @Api(description = "User center") public class UserController { @GetMapping("/error1") public User error1(Integer id) { if (id.equals(1)) { throw new RuntimeException("Incorrect user name and password!!!"); } User user = new User(); user.setId(1); user.setNickname("yykk"); user.setPassword("451212"); user.setAddress("Meizhou"); return user; } @GetMapping("/error2") public User error2(Integer id) { int i = 1 / 0; User user = new User(); user.setId(1); user.setNickname("yykk"); user.setPassword("451212"); user.setAddress("Meizhou"); return user; } @GetMapping("/getuser") public User getuser(Integer id) { User user = new User(); user.setId(1); user.setNickname("yykk"); user.setPassword("451212"); user.setAddress("Meizhou"); return user; } @ResponseBody //---Mark -- does jackson A have B @GetMapping("/getname") public String getusername() { return "yykk"; } }
Custom exception and integrated custom exception handler
The advantages of user-defined exception are: it can quickly locate the module where the error occurs according to the information of self-defined exception, facilitate the recording of log files, and quickly analyze and determine the error.