SpringBoot全局捕获异常并返回给前端

1.自定义一个异常类:

public class RuleException extends RuntimeException {
    private static final long serialVersionUID = -8624533394127244753L;

    public RuleException() {
    }

    public RuleException(String msg) {
        super(msg);
    }

    public RuleException(Exception ex) {
        super(ex);
        ex.printStackTrace();
    }
}

2.返回给前端的实体类:

public class Result {

    private String code;

    private String message;

    private String status;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

3.ExceptionAdvice类

import com.christopher.rule.RuleException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@ControllerAdvice //@ControllerAdvice(控制器增强。该注解可以把其声明的类中使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到所有的 @RequestMapping注解的方法)声明一个拦截全局异常的@ExceptionHandler
public class ExceptionAdvice {

    @ExceptionHandler(RuleException.class) //@ExceptionHandler拦截相应异常
    @ResponseBody
    public Result handleException(Exception e) {
        Result result = new Result();
        result.setStatus("500");
        result.setMessage(e.getMessage());
        return result;
    }
}

4.效果

posted @ 2022-09-26 14:03  AboutChristopher  阅读(557)  评论(0编辑  收藏  举报