全局异常处理-springboot

本文介绍如何在Java中自定义异常类MyException和MyRuntimeException,并通过@ControllerAdvice注解创建全局异常处理器MyExceptionHandler,处理并返回统一的错误信息。

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

1.定义异常处理类

public class MyException extends Exception{

    private static final long serialVersionUID = -5519743897907627214L;

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

}

public class MyRuntimeException extends RuntimeException {

    private static final long serialVersionUID = -6925278824391495117L;

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

}

 

2.异常处理器

@ControllerAdvice
@ResponseBody
public class MyExceptionHandler {

    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Map<String, Object> handlerMyException(MyException ex) {
        Map<String,Object> result = new HashMap<>();
        result.put("message", ex.getMessage());
        result.put("code", 300);
        return result;
    }

    @ExceptionHandler(MyRuntimeException.class)
    @ResponseBody
    public Map<String, Object> handlerMyRuntimeException(MyRuntimeException ex) {
        Map<String,Object> result = new HashMap<>();
        result.put("message", ex.getMessage());
        result.put("code", 300);
        return result;
    }
}

3.在抛出异常时打印信息为

{

"code":300,

"message":"自定义异常信息"

}

@ControllerAdvice
@ResponseBody

没有加这个注解返回信息是

{
    "timestamp": "2018-12-20 15:19:46",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Request processing failed; nested exception is **Exception: 用户未登录或会话过期",
    "path": "/"
}

 

原文参考:https://blog.youkuaiyun.com/smollsnail/article/details/79143007

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值