java全局异常处理

本文介绍了如何在SpringBoot项目中创建自定义BusinessException,并通过@RestControllerAdvice和ExceptionHandler注解实现对不同类型的异常进行统一处理,确保优先匹配业务异常并返回适当的状态码和错误信息。
摘要由CSDN通过智能技术生成

自定义异常类


import lombok.Data;

@Data
public class BusinessException extends RuntimeException{

    private Integer code;

    public BusinessException(String message) {
        super(message);
        this.code = 500;
    }

    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public BusinessException(Integer code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }
}

统一异常处理


import com.example.mybatisplusdemo.util.ResultUtil;
import com.example.mybatisplusdemo.vo.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BusinessException.class)
    public Result handle(BusinessException e){
        return ResultUtil.fail(e.getCode(),e.getMessage());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result handle(Exception e){
        return ResultUtil.fail(500,e.getMessage());
    }

}
  • 会优先匹配自己的异常,如果匹配不到,就走exception
  • handle写的顺序无关
  • 20
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值