Spring Boot 自定义异常处理

本文介绍了如何在Spring Boot中实现自定义异常处理,包括创建自定义异常类并继承RuntimeException,设置全局异常处理器,定义响应结果枚举类,以及进行自定义异常处理的测试。

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

自定义异常类,继承RuntimeException

/**
 * 自定制异常类
 *
 * @author MoCha
 * @date 2019/5/25
 */
@Getter
public class CustomException extends RuntimeException {
    private int code;
    private String message;

    public CustomException(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public CustomException(ResultStatusEnum resultStatusEnum) {
        this.code = resultStatusEnum.getCode();
        this.message = resultStatusEnum.getMessage();
    }
}

全局异常处理

/**
 * 全局异常处理
 *
 * @author MoCha
 * @date 2019/5/25
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public Map<String, Object> handleCustomException(CustomException customException) {
        Map<String, Object> errorResultMap = new HashMap<>(16);
        errorResultMap.put("code", customException.getCode());
        errorResultMap.put("message", customException.getMessage());
        return errorResultMap;
    }
}

响应结果枚举类

/**
 * 响应结果状态枚举类
 *
 * @author MoCha
 * @date 2019/5/25
 */
@NoArgsConstructor
@AllArgsConstructor
public enum ResultStatusEnum {
    /**
     * 请求成功
     */
    SUCCESS(200, "请求成功!"),

    /**
     * 密码错误
     */
    PASSWORD_NOT_MATCHING(400, "密码错误");

    @Getter
    @Setter
    private int code;

    @Getter
    @Setter
    private String message;
}

测试自定义异常处理

@GetMapping("/test/{id:\\d+}")
public UserDTO testError(@PathVariable("id") String userId) {
    throw new CustomException(ResultStatusEnum.PASSWORD_NOT_MATCHING);
}

@GetMapping("/test2/{id:\\d+}")
public UserDTO testError2(@PathVariable("id") String userId) {
    throw new CustomException(400, "这是400错误");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值