Public exception handling class

premise

In order to make the code easy to maintain and reduce redundancy, we create a class to handle exceptions centrally
. Create a public exception handling class BaseExceptionHandler under the **.controller package, and add code

coding

package com.tensquare.article.controller;

import entity.Result;
import entity.StatusCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class BaseExceptionHandler {
    
    
//这里是用的异常最高级,每一个controller其实根据自身的业务逻辑来实现处理异常类最好
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handler(Exception e) {
    
    
        System.out.println("处理异常");

        return new Result(false, StatusCode.ERROR, e.getMessage());
    }

}

Test exception (for testing)

//测试公共异常处理
    @RequestMapping(value = "exception", method = RequestMethod.GET)
    public Result test() {
    
    
        int a = 1 / 0;

        return null;
    }


Guess you like

Origin blog.csdn.net/weixin_47785112/article/details/109296417