The article directories

Preface and need to use annotations, global exception handling code 1. Create GlobalExceptionHandler. Java 2. Java class globalExceptionTest method 3. Summary of case operation effect


preface

We believe that we are familiar with exceptions, there are predictable and some unknown exceptions, usually we will do the escape unified return processing for exceptions, so as to be able to better locate the program problem, due to too much exception handling, our code try… There will be a lot of catches, and the code will look messy, untidy, redundant, and people will say, well, what if I didn’t write it this way? Don’t panic, this chapter takes you from trying… Save from the catch, we go down to 👇


1. Annotations to be used

@controllerAdvice Controller enhancer. This annotation is used to control the Controller scope by specifying the package name/concrete class. @ExceptionHandler(value = exception.class) This annotation is used to handle ExceptionHandler exceptions. With the @resquetMapping method, exceptions will enter the @ExceptionHandler annotation method. We could have written a method in a single Controller class with the @ExceptionHandler annotation, but each Controller class would still be redundant, so the @ControllerAdvice annotation would have the same effect.

Second, global exception capture code implementation

1.

Create abnormal processing GlobalExceptionHandler class. Java, new exceptionHandler methods were reviewed and exception information encapsulation process the return. The exceptionHandler method does more to handle exceptions: 1. Special handling of login and permission related exceptions 2. Special handling of different service exceptions 3. Unified exception response codes and error information 3. Unified exception log printing… More sample code:

package com.example.demo.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

     @ResponseBody
     @ExceptionHandler
     public Map<String, Object> exceptionHandler(HttpServletRequest req, Exception e) {
        log.info("url : {} , exception : {}", req.getRequestURI(), e.getMessage());
        Map<String, Object> ret = new HashMap<>();
        ret.put("url", req.getRequestURI());
        ret.put("exception", e.getMessage());
        returnret; }}Copy the code

2.

Java class and globalExceptionTest method to throw an Exception directly

package com.example.demo.controller;

import com.example.demo.dto.JsonDataDTO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class DemoController {

    @GetMapping("/test")
    public String test(a) {
        return "Hello World";
    }

    @RequestMapping("/getJsonData")
    public JsonDataDTO getJsonData(a) {
        JsonDataDTO jsonDataDTO = new JsonDataDTO();
        jsonDataDTO.setName("Zhang");
        jsonDataDTO.setAge(18);
        jsonDataDTO.setSex("Male");
        return jsonDataDTO;
    }

    @RequestMapping("/globalExceptionTest")
    public void globalExceptionTest(a) throws Exception {
        throw new Exception("There is an exception!!"); }}Copy the code

3.

Case running effect, start the project visit: http://localhost:8080/globalExceptionTest

Program run log:

2020-10-26 11:43:09.769  INFO 77800 --- [nio-8080-exec-1] C.E.D.I.G lobalExceptionHandler: url: / globalExceptionTest, exception: abnormal happen!!!2020-10-26 11:43:09.865  WARN 77800 --- [nio-8080-exec-1]. M.M.A.E xceptionHandlerExceptionResolver: Resolved [Java. Lang. Exception: abnormal happen!!!]Copy the code

conclusion

In this chapter we will learn how to use @ControllerAdvice and @ExceptionHandler annotations to globally catch exceptions to reduce the number of tries… Catch coding as well as abnormal escape and so on, to reduce the amount of code and improve code cleanliness level, standardized development to avoid repetition of rolling, point a praise like friends, pay attention to my last update SpringBoot series, if there is any doubt welcome comments, small make up will prompt reply oh ~ like classmates began to show a great, collection!

More good articles please pay attention to the public number: main method