This is the first day of my participation in the August Text Challenge.More challenges in August

Springboot global exception handling and unified response object

Springboot exception processing

The default exception handling mechanism for SpringBoot

By default, SpringBoot provides two different responses

  1. One is when a browser client requests a non-existent page or a server exception, SpringBoot responds with an HTML by default

  2. The other is to usepostmanIf the debugging tool requests a non-existent URL or a server exception, json information is returned by default

SpringBoot Global exception processing

Normally we don’t want to return the error message to the front end and try catch the exception ourselves, but there is a problem: it is not appropriate for every method to catch an exception in this way, so we need global exception handling.

@RestController public class ExceptionController { @GetMapping("exceptionA") public void methodA() { try { int a = 100 / 0; } catch (Exception e) { e.printStackTrace(); }}}Copy the code

1. Handle local exceptions

Implement local exception handling for a class using the @eceptionHandle annotation

@RestController public class ExceptionController { @GetMapping("exceptionA") public void methodA() { int a = 100 / 0; } /** * ExceptionHandler(exception.class) public String ExceptionHandler(exceptione) {// ExceptionHandler(exception.class) public String ExceptionHandler(exceptione) {// ExceptionHandler(exceptione) public String ExceptionHandler(exceptione) Instanceof ArithmeticException) {return "division by 0 exception occurred "; } // return "an unknown exception occurred "; }}Copy the code

2. Handle global exceptions

Use the @ControllerAdvice +@ExceptionHandler annotation for global exception handling

Customize an exception class

@RestControllerAdvice public class DefaultException { @ExceptionHandler({NullPointerException.class}) public String Exception (NullPointerException exception) {return "NullPointerException "; } @ExceptionHandler({IndexOutOfBoundsException.class}) public String exception(IndexOutOfBoundsException exception) { Return "array out of bounds exception "; }}Copy the code

Added an exception method test, commented out because local exceptions have higher priority

@RestController public class ExceptionController { @GetMapping("exceptionA") public void methodA() { int a = 100 / 0; } @GetMapping("exceptionB") public void methodB() { List list = new ArrayList<>(); System.out.println(list.get(0)); // / @exceptionHandler (exception.class) // Public String ExceptionHandler(Exception e) {// // // if (e instanceof ArithmeticException) {// return "Division 0 exception occurred "; //} // // respond to an unknown exception // return "An unknown exception occurred "; / /}}Copy the code

The global exception annotation is in effect

Custom exception

A custom exception only needs to inherit from the Exception class or its subclasses

@Data @NoArgsConstructor public class CustomException extends Exception { private static final long serialVersionUID = 1L; private Integer code; private String mes; /** * @param code status code * @param MSG exception message * @description constructor */ public CustomException(Integer code, String msg) { super(msg); this.code = code; }}Copy the code

When used, exception objects can be thrown directly

@GetMapping("exceptionC") public void methodC() throws CustomException { int a = 1; If (a == 1) {throw new CustomException(10086, "CustomException "); }}Copy the code

Unified Response object

In practical development, we need to encapsulate unified response objects and distinguish status codes and information for front-end processing.

1. Define unified response objects

Generally contains status codes, error messages, data, etc.

Customize some methods to return information, such as the SUCCESS (),failed() methods I defined

@data@noargsconstructor @allargsconstructor public class constructor R<T> {/** * private Integer code; /** * return message */ private String MSG; /** * data */ private T data; public static R success() { return new R(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), null); } public static R success(Object data) { return new R(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), data); } public static R failed() { return new R(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMsg(), null); } public static R failed(String msg) { return new R(ResultCode.FAILED.getCode(), msg, null); } public static R failed(int code, String msg) { return new R(code, msg, null); }}Copy the code

Enumeration information

Enumerates some common state information

I’ll give you an example, just enumerate 2, customize as needed

@noargsconstructor @allargsconstructor Public enum ResultCode {SUCCESS(200, "request SUCCESS "), FAILED(500," server error "); private int code; private String msg; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; }}Copy the code

The response object

When used, directly return the defined object type on the line, the defined global exception return type also changed to the unified response object

@RestControllerAdvice public class DefaultException { @ExceptionHandler({CustomException.class}) public R exception(CustomException e) { return R.failed(e.getCode(),e.getMessage()); } @ExceptionHandler({Exception.class}) public R exception(Exception e) { return R.failed(e.getMessage()); }}Copy the code

So much for a brief introduction to global exceptions and response objects.

Gitee address: gitee.com/rainscloud/…