Spring全局异常处理

直接放上代码,使用@RestControllerAdvice进行controller层的处理

/**
 * @author Relic
 */
@Slf4j
@RestControllerAdvice
public class BusinessExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessException(BusinessException e) {
        return new Result(false, e.getMsg(), 500);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handlerNoFoundException(Exception e) {
        log.error(e.toString(), e);
        return new Result(false, "路径不存在,请检查路径是否正确", 404);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.toString(), e);
        return new Result(false, "数据库中已存在该记录", 500);
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        return ResultUtils.exceptionResult(e);
    }
}

RestControllerAdvice无法处理404,此处解决404

/**
 * @author Relic
 * @desc 404错误处理
 * @date 2019-05-15 14:34
 */
@RestController
public class NotFoundController implements ErrorController {

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    public Result error() {
        return new Result(false, "路径不存在,请检查路径是否正确", 404);
    }
}

自定义异常类

/**
 * @author Relic
 * @desc 业务异常
 * @date 2019-03-08 17:30
 */
@Getter
@Setter
@ToString
public class BusinessException extends RuntimeException {

    private int code = 500;
    private String msg;

    public BusinessException(String msg) {
        super(msg);
        this.msg = msg;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值