Spring Boot2.x 自定义异常处理

本文详细介绍了如何在SpringBoot2.x中自定义异常处理流程。首先定义了一个AccountException异常类,然后创建了AccountExceptionHandler处理器来捕获并处理AccountException,最后在业务代码中演示了如何抛出自定义异常。

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

Spring Boot2.x Web MVC 自定义异常处理

1.定义异常

public class AccountException extends RuntimeException {

    public AccountException() {
        super();
    }

    public AccountException(String message) {
        super(message);
    }

    public AccountException(String message, Throwable cause) {
        super(message, cause);
    }

    public AccountException(Throwable cause) {
        super(cause);
    }
}

2.定义异常处理器

@RestControllerAdvice
public class AccountExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(AccountException.class)
    Response handleControllerException(HttpServletResponse response, Throwable ex) {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return Response.exception(ex.getMessage());
    }

}

3.业务代码

抛出异常:

    public Account createAccount(Account account) {
    throw new AccountException("账务业务异常");
    //    return accountRepository.save(account);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值