Spring Boo 全局异常处理

本文介绍SpringBoot中通过@ControllerAdvice+@ExceptionHandler及@Controller+@ExceptionHandler两种方式处理异常的方法,并提供了具体的代码示例。

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

1、概述

Spring Boot 处理异常的两种方式:
1) @ControllerAdvice + @ExceptionHandler:配置对全局异常进行处理
2) @Controller + @ExceptionHandler:配置对当前所在Controller的异常进行处理

2、实战

2.1、@ControllerAdvice + @ExceptionHandler:配置对全局异常进行处理

创建需要定义的异常, 或者是使用java自带

public class ZkOperationException extends RuntimeException {

    private static final long serialVersionUID = 4708512975487042443L;
    private Integer code;
    private String msg;

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

    public ZkOperationException(PromptMessageCode code){
        super(code.toString());
        this.code = code.getCode();
        this.msg = code.getMsg();
    }

    public ZkOperationException(PromptMessageCode code, Throwable cause) {
        super(code.toString(), cause);
        this.code = code.getCode();
        this.msg = code.getMsg();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

定义异常处理类

@ControllerAdvice
public class GlobalExceptionHandler extends BaseResponse{

    @ExceptionHandler(value = ZkOperationException.class)
    @ResponseBody
    public CommonResponse jsonErrorHandler(HttpServletRequest req, ZkOperationException e){
       return getResultFailure(null, e.getMsg());
    }
}

当在调用的地方, 出错后抛出ZkOperationException 这个异常, 进行处理, 当然如果有多种类型可以, 直接使用Exception。

2.2 @Controller + @ExceptionHandler:配置对当前所在Controller的异常进行处理

创建controller

@Controller
@RequestMapping("userAndZkBind")
public class UserAndZkBindController extends BaseController {

    @Autowired
    private ZkInfoService zkInfoService;

    @RequestMapping(value = "/applyZkConnectionInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse<ZkConnectionInfo> applyZkConnectionInfo(){

        // 这里是业务内容不写。
        return null;
    }

    @ExceptionHandler(ZkOperationException.class)
    public CommonResponse HandlerErrorJson(HttpServletRequest request, Exception ex){
        return getResultFailure(null, ex.getMessage());
    }
}

3、总结

两种方法都可以对异常进行处理, 返回预定义的提示信息。
读者可以根据实际情况, 进行相应的操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值