Java Springboot Global Exception Handling

  • 2021-12-05 06:15:14
  • OfStack

Preface to the catalogue 1. Ideas? 2. Step 1. Custom interface: 2. Custom error enumeration 3. Custom exception class 4. Exception catch 5. Throw exception summary in code

Preface

As a novice programmer, I often use try-catch to wrap my service layer code in controller. The first page is not good-looking. Secondly, every method has this code block. Think about whether there is a way to get rid of it and handle exceptions gracefully. This is what we are going to talk about today, global exception catching

Tip: The following is the main content of this article, and the following cases can be used for reference

1. Thinking?

springboot provides annotations for global exception handling, and what we need to understand is that. What exceptions are caught, and if the results are returned, how to gracefully manage the returned result set.

Step 2 Steps

1. Customize the interface:

Custom interface mainly describes returned code code and returned msg. Custom error description enumeration needs to implement this interface


public interface ErrorType {
    /**
     *  Return code
     *
     * @return
     */
    String getCode();
    /**
     *  Return mesg
     *
     * @return
     */
    String getMesg();
}

2. Custom error enumeration

With enumerations, the code looks elegant, and you don't have to use static final to define types.


@Getter
public enum SystemErrorType implements ErrorType {
    SYSTEM_ERROR("-1", " System anomaly "),
    SYSTEM_BUSY("000001", " The system is busy , Please try again later ");
    /**
     *  Error type code 
     */
    private String code;
    /**
     *  Error type description information 
     */
    private String mesg;
    SystemErrorType(String code, String mesg) {
        this.code = code;
        this.mesg = mesg;
    }
}

3. Custom exception classes


@Getter
public class MyException extends RuntimeException{
    /**
     *  Error type corresponding to exception 
     */
  private final ErrorType errorType;
   /**
    *  The default is system exception 
    */
   public MyException () {
       this.errorType = SystemErrorType.SYSTEM_ERROR;
   }
   public MyException(SystemErrorType systemErrorType) {
	   this.errorType = systemErrorType;
    }

4. Exception catching


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandlerAdvice extends DefaultGlobalExceptionHandlerAdvice {
    @ExceptionHandler(value = {MyException .class})
    public Result MyException (MyException ex) {
        log.error(ex.getMessage());
        return Result.fail(ex.getErrorType());
    }
    @ExceptionHandler(value = {NotRoleException.class})
    public Result NotRoleException(NotRoleException nle) {
        //  Print the stack for debugging 
        //nle.printStackTrace();
        String message = " This function is only available for "+nle.getRole()+" Use !";
        //  Back to the front end 
        return Result.fail("090017",message,null);
    }
}

It is not to say that you can only return by enumeration, as long as your return tool class supports parameter filling, you can do similar return to the second type, but this method is too easy to manage the returned code

5. Throw an exception in your code

For example, when I do empty judgment, I use enumeration as a parameter to return


    @PostMapping("/listQuestionVO")
    public Result listQuestionBankVO(@RequestBody QuestionBankQuery query){
        if (query.getPageNum()==null || query.getPageSize()==null){
            return Result.fail(QuestionnaireErrorType.PARAMETERISNULL_ERROR);
        }
        Result result = questionBankService.listQuestionBankVO(query);
        return result;
    }

In fact, you can directly throws exceptions where you need to handle them, and you can directly throw throws on the method, waiting for the global exception to be caught

Summarize

As long as the management code is in place, it is more suitable for Xiaobai to replace the enumeration with the tool class of the return type

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: