如何使用@ControllerAdvice注解配置全局异常处理器?

在 Spring 中,可以使用@ControllerAdvice注解来配置全局异常处理器,以下是具体步骤:

一、创建全局异常处理类

  1. 创建一个类,并使用@ControllerAdvice注解进行标注。

    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.ResponseStatus;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @ControllerAdvice
    public class GlobalExceptionHandler {
        // 异常处理方法将在这里定义
    }
    

二、定义异常处理方法

  1. 使用@ExceptionHandler注解来指定要处理的异常类型。例如,要处理所有的Exception异常,可以这样写:

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Map<String, Object> handleException(Exception e) {
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("message", "An unexpected error occurred.");
        errorResponse.put("error", e.getMessage());
        return errorResponse;
    }
    

    在这个方法中,当发生任何Exception异常时,会返回一个包含错误信息的 JSON 响应,并设置 HTTP 状态码为 500(内部服务器错误)。

  2. 你可以根据不同的异常类型定义多个异常处理方法。例如,处理特定的业务异常:

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Map<String, Object> handleBusinessException(BusinessException e) {
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("message", e.getMessage());
        return errorResponse;
    }
    

三、异常处理逻辑

在异常处理方法中,你可以根据具体的需求进行错误信息的封装和返回。可以返回自定义的错误对象,或者直接返回一个包含错误信息的Map等。

通过以上步骤,你就可以使用@ControllerAdvice注解配置一个全局异常处理器,统一处理应用程序中的异常情况,提高应用的稳定性和可维护性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值