SpringBook entry note 17—— global exception handling and custom exception handling

Posted by noon on Tue, 14 May 2019 13:38:11 +0200

Global exception handling and custom exception

Article directory

1. Catching global exceptions

Capturing global exceptions is actually very simple, and requires only two annotations. First, create an exception capture class, such as CustomExtHandler

package com.michael.study.domain;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * Author Google
 * Time 2019/4/15 11:19
 * File Custom ExtHandler
 * Describe exception handling classes
 */

@RestControllerAdvice
public class CustomExtHandler {

    private static final Logger logger = LoggerFactory.getLogger(CustomExtHandler.class);

    /**
     * Capture global exceptions
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    //@ResponseBody
    Object handleException(Exception e, HttpServletRequest request) {
        //Output our log log
        logger.error("url {},msg{}",request.getRequestURL(),e.getMessage());
        Map<String, Object> map = new HashMap<>();
        map.put("msg", e.getMessage());
        map.put("code", 0);
        return map;
    }
}

The above code completes self-trapping of global exceptions and returns the specified information.

  • The first step is to add the @RestController Advice annotation on the class to indicate the controller recommendation and return it in json format.
  • The second step is to write a method to catch exceptions and receive two parameters, Exception and HttpServletRequest.
  • The third step is to add the annotation @ExceptionHandler(value = Exception.class) to the method to indicate that the level of exception to be received is Exception, which is the global exception.
  • Step 4: Write the data that needs to be returned to the front end

Note that there is another way to add two annotations to the method with the annotation @ControllerAdvice on the class

@ ExceptionHandler(value = Exception.class) and @ResponseBody result are the same. It's all about having custom data return in json format.

At this point, we can write a controller to trigger an exception manually, such as

    @GetMapping("/v1/api/test")
    public Object testException(){
        Map<String,String > params=new HashMap<>();
        params.put("b","Gone, brother.");
        params.put("a","Here we go.");
        int a=10/0;
        return params;
    }

Then run the program, call the interface, and it will appear.

{
    "msg": "/ by zero",
    "code": 0
}

As you can see, our exception is returned in our custom format.

2. Custom exceptions

To customize exceptions, the first thing we need to do is to customize exceptions classes

2.1 Custom Exception Class

package com.michael.study.exception;

/**
 * Time 2019/4/15 11:47
 * File MyException
 * Describe custom exception classes
 */
public class MyException extends RuntimeException {
    private String code;
    private String msg;

    public MyException(String code,String msg){
        this.code=code;
        this.msg=msg;
    }

    public String getCode() {
        return code == null ? "" : code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg == null ? "" : msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

Our custom exception class has only two parameters, one is the status code and the other is the exception message. The next thing we need to do is to capture our custom exception in the exception handling class.

2.2 Handling custom exceptions

In the exception handling class CustomExtHandler created above, add our custom exception, the complete code is as follows:

package com.michael.study.domain;

import com.michael.study.exception.MyException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * Author Google
 * Time 2019/4/15 11:19
 * File Custom ExtHandler
 * Describe exception handling classes
 */

@RestControllerAdvice
public class CustomExtHandler {

    private static final Logger logger = LoggerFactory.getLogger(CustomExtHandler.class);

    /**
     * Capture global exceptions
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    //@ResponseBody
    Object handleException(Exception e, HttpServletRequest request) {
        //Output our log log
        logger.error("url {},msg{}",request.getRequestURL(),e.getMessage());
        Map<String, Object> map = new HashMap<>();
        map.put("msg", e.getMessage());
        map.put("code", 0);
        return map;
    }

    /**
     * Custom exception handling
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = MyException.class)
    Object handleMyException(MyException e, HttpServletRequest request){

        logger.error("url {},msg{}",request.getRequestURL(),e.getMessage());
        Map<String, Object> result = new HashMap<>();
        result.put("msg", e.getMsg());
        result.put("code", e.getCode());
        return result;

    }
}

We also captured our custom exception here through @RestController Advice and @ExceptionHandler(value = MyException.class) annotations. When somewhere in our code we throw MyException exceptions, we capture them here, and then we print the next log here and return information about our custom exceptions.

2.3 summary

Customize exceptions, we just demonstrated above, so it's better to name them more standardized, and can you agree on their own exception status, work with team members to develop exception specifications, return the appropriate exception information. The approximate steps are as described above.

  • Create exception classes to throw exceptions
  • Create exception handling classes to catch exceptions
  • Two key annotations @RestController Advice and @ExceptionHandler(value = custom exception class name. class)
  • If the thrown exception is not captured, it is captured by the defined global exception.

Topics: Java Google JSON