springboot项目中的异常处理

本文介绍如何在Java中自定义异常类并实现全局异常处理。通过继承RuntimeException创建自定义异常,如NotFoundException,并在全局异常处理类中注册这些异常,以统一处理不同类型的错误,提高代码的健壮性和可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.首先自定义异常类继承RuntimeException类,以NotFoundException为例:

使用MessageFormat.format()方法做信息和可变参的处理。

public class NotFoundException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public NotFoundException(String msg, Object... obj) {
        super(MessageFormat.format(msg, obj));
    }
}

2.定义全局异常处理类,将自定义的异常注册到其中。

@RestControllerAdvice
@Component
public class GlobalDefaultExceptionHandler {

    /**
     * 404异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorMsg notFoundException(NotFoundException e) {
        return new ErrorMsg(404, e.getMessage());
    }

    /**
     * 409异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(ExistedException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    public ErrorMsg existedException(ExistedException e) {
        return new ErrorMsg(409, e.getMessage());
    }

    /**
     * 403
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(UnAuthenticationException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ErrorMsg unAuthenticationException(UnAuthenticationException e) {
        return new ErrorMsg(403, e.getMessage());
    }

    /**
     * 400 json格式异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(JsonSchemaException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorMsg jsonSchemaException(JsonSchemaException e) {
        return new ErrorMsg(400, e.getMessage());
    }

}

3.接下来只要在需要抛出异常的位置,抛出自定义异常即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值