Moment For Technology

Spring Cloud unify exception handling and catching exceptions

Posted on Sept. 23, 2022, 9:42 a.m. by Kiaan Bir
Category: The back-end Tag: The back-end java

There are a variety of runtime exceptions during program development, sometimes unpredictable, sometimes special exceptions for business needs and sometimes special handling of different exceptions

@ExceptionHandler: handles ExceptionHandler for a certain type of exception. @ControllerAdvice: Handles ExceptionHandler centrally to better separate the service logic from exception handling. @responseStatus: Specifies the HTTP status code for exceptional responses


Define a global exception catching class


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/** * Global exception catch processing **@author Administrator
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    /** * Exception catch, the catch type is :Exception, except for custom types should be caught **@param e
     * @return* /
    public String handleException(Exception e) {"System exception :{}", e);

        // Write the exception handling logic

        / / proposal format return data of unity, reference:
        //return new Result(ResultCodeEnum.NO);
        return "{ \"code\" : 0, \"msg\" : \"" + e + "\"}";

    /** * User-defined service exceptions. The catch type is BizException. Only BizException exceptions can be caught@param e
     * @return* /
    public String handleBizException(BizException e) {"Service exception :{}", e);

        // Write the exception handling logic
        / / proposal format return data of unity, reference:
        //return new Result(e.getCode(), e.getMsg());
        return "{ \"code\" : " + e.code + ", \"msg\" : \"" + e.msg + "\"}";

    // You can append other custom exceptions, like BizException
Copy the code

Suggested format return data of unity, reference:


2. Customize service exceptions


import lombok.Data;

/** * User-defined service exception **@author Administrator
public class BizException extends RuntimeException {

    /** * error code */
    protected Integer code;

    /** * error message */
    protected String msg;

    public BizException(Integer code, String msg){
        this.code = code;
        this.msg = msg; }}Copy the code


Customize service exceptions


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/ * * *@author Administrator
@api (value = "test class ", tags =" test class ")
public class TestApiController {

    @apiOperation (value = "test Exception1 ", httpMethod = "GET")
    public String exception1(a){
        if(true) {/ / advice can define a business exception enumeration: reference
            throw new BizException(3."Error 3");

        return "OK";

    @apiOperation (value = "test Exception2 ", httpMethod = "GET")
    public String exception2(a){
            Integer A = 1/0;

        return "OK"; }}Copy the code

Advice can define a business exception enumeration: reference

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.