Java统一异常全局处理

本文最后更新于:2025年6月25日 晚上

添加自定义异常: BusinessException.java

import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author Smile
 * @version 1.0
 * @description: TODO
 * @date 2022/3/31 17:09
 */

@Data
@NoArgsConstructor
public class BusinessException extends RuntimeException{
    // 状态码
    private Integer code;

    // 错误信息
    private String message;
}

创建统一异常处理类: XXXExceptionHander.java

import com.hh.core.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Smile
 * @version 1.0
 * @description: TODO
 * @date 2022/3/30 9:30
 */
@Component
@RestControllerAdvice
@Slf4j
public class MYRExceptionHander {
    @ExceptionHandler(BusinessException.class)
    public Result BusinessException(BusinessException e){
        log.error(e.getMessage());
        return Result.fail().message(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = RuntimeException.class)
    public Result RunTimeExceptionHander(RuntimeException e) {
        log.error(e.getMessage());
        return Result.fail();
    }

    @ExceptionHandler(value = Exception.class)
    public Result AllExceptionHander(Exception e) {
        log.error(e.getMessage());
        return Result.fail();
    }
}

当发生的异常被抛出时,会由标有 @RestControllerAdvice注解的类进行处理,若没有匹配到相应的异常,则有最大的异常”Exception”进行处理。


Java统一异常全局处理
https://codeofhh.cn/2022/04/03/Java统一异常全局处理/
作者
hhu
发布于
2022年4月3日
许可协议