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

package com.pd.shop.exception;

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})
@Slf4j
public class GlobalExceptionHandler {

    /** * Exception catch, the catch type is :Exception, except for custom types should be caught **@param e
     * @return* /
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        log.info("System exception :{}", e);

        // Write the exception handling logic

        / / proposal format return data of unity, reference: https://preparedata.blog.csdn.net/article/details/114667202
        //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* /
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(BizException.class)
    public String handleBizException(BizException e) {
        log.info("Service exception :{}", e);

        // Write the exception handling logic
        
        / / proposal format return data of unity, reference: https://preparedata.blog.csdn.net/article/details/114667202
        //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: preparedata.blog.csdn.net/article/det...

\

2. Customize service exceptions

package com.pd.shop.exception;

import lombok.Data;

/** * User-defined service exception **@author Administrator
 */
@Data
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

package com.pd.shop.controller;

import com.pd.shop.exception.BizException;
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 ")
@RestController
@RequestMapping("/v1/testApi")
public class TestApiController {

    @GetMapping("/exception1")
    @apiOperation (value = "test Exception1 ", httpMethod = "GET")
    public String exception1(a){
        if(true) {/ / advice can define a business exception enumeration: reference https://preparedata.blog.csdn.net/article/details/114670846
            throw new BizException(3."Error 3");
        }

        return "OK";
    }

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

        return "OK"; }}Copy the code

Advice can define a business exception enumeration: reference preparedata.blog.csdn.net/article/det...

Search
About
mo4tech.com (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.