preface

Exception handling is one of the most important aspects of our back-end development, which relates to our ability to communicate effectively with the front end.

Here’s a scenario:

Xx front end: XX background, your interface error, come to see.

Xx backend: how possible, reported what wrong

Xx front-end: do not know, is to display server error. I don’t know.

Xx back end silently open the log, began to search for errors. After some efforts, finally found that the original is the front desk error.

Then the background began to communicate with the front end, began to explain how to pass the parameter…

By now the better part of an hour had passed

This scenario, which we can say happens all the time, is how we can effectively return error types and prompt messages. This will greatly improve our development efficiency. I wonder if we’ll have more time to study

Exception handling in Spring 3 big notes

  • ExceptionHandler: Uniformly handles a class of exceptions to reduce code duplication and complexity
  • ControllerAdvice: Centralize exception handling to better separate business logic from exception handling. It intercepts the Controller layer
  • ResponseStatus: An exception can be mapped to an HTTP status code

In SpringBoot, the AOP container idea is used, which is simply summed up as adding annotations to the container and then injecting them where needed. If you don’t understand it, you should know about it.

With these three annotations, we are ready to handle our exceptions.

The code field

Public class UnifyResponse {private int code; public class UnifyResponse {private int code; public int getCode() { return code; } public String getMessage() { return message; } public String getRequest() { return request; }}Copy the code
Http. codes[30003] = code type 1 HTTP. Codes [30005] = code type 2Copy the code

Exception-code.properties file location

ExceptionCodeConfiguration. Java / / read the configuration file import org. Springframework. Boot. The context. The properties. ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @configurationProperties (prefix = "HTTP ") HTTP. Codes can use codes instead of @ PropertySource (value = "classpath: config/exception - code. The properties") / / configuration file path @ Component / / container public class ExceptionCodeConfiguration { private Map<Integer, String> codes = new HashMap<>(); public Map<Integer, String> getCodes() { return codes; } public void setCodes(Map<Integer, String> codes) { this.codes = codes; } public String getMessage(int code){ String message = codes.get(code); return message; }}Copy the code
Public class HttpException extends RuntimeException {protected Integer code; public Integer getCode() { return code; } public Integer getHttpStatusCode() { return httpStatusCode; } protected Integer httpStatusCode = 500; }Copy the code
NotFoundException. Java // Specific error type, Public class NotFoundException extends HttpException {public NotFoundException(int code){this.httpStatusCode = 404; this.code = code; }}Copy the code
GlobalExceptionAdvice. Java file @ ControllerAdvice / / / / global error processing can capture error of contrller public class GlobalExceptionAdvice { @Autowired private ExceptionCodeConfiguration codeConfiguration; @exceptionHandler (value= exception.class) // Common error type @responseBody // add this, Return @responseStatus (code= httpstatus. INTERNAL_SERVER_ERROR handleException(HttpServletRequest req, Exception e) { String requestUrl = req.getRequestURI(); String method = req.getMethod(); // Request method system.out.println (e); UnifyResponse message = new UnifyResponse(9999, "server exception ", method +" "+ requestUrl); return message; } @exceptionHandler (httpException.class) public ResponseEntity<UnifyResponse> handleHttpException(HttpServletRequest req, HttpException e){ String requestUrl = req.getRequestURI(); String method = req.getMethod(); UnifyResponse message = new UnifyResponse(e.getCode(),codeConfiguration.getMessage(e.getCode()), method + " " + requestUrl); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); HttpStatus httpStatus = HttpStatus.resolve(e.getHttpStatusCode()); // ResponseEntity contains the header information, which is returned to the front end and wrapped around the UnifyResponse. ResponseEntity<UnifyResponse> r = new ResponseEntity<>(message, headers, httpStatus); return r; }}Copy the code

So how do we trigger our errors? Quite simply, a simple Contrller interface is defined to determine if the banner exists and throw an error if it does not.

Finally, let’s take a look at the directory structure:

Well, today’s global exception sharing is over, if you have any questions can communicate with me oh. If it works for you, thank you. Back to old age commercials