JAVA全局异常处理

import com.jd.fastjson.JSON;
import com.jdl.lomir.ai.box.adaptor.web.base.response.ApiResponse;
import com.jdl.lomir.ai.box.component.base.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>异常处理</p>
 *
 * @author manhengwei
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理运行时异常.
     */
    @ExceptionHandler(value = {BusinessException.class})
    @ResponseBody
    public final ApiResponse<?> handleBusinessException(BusinessException e) {
        log.error(e.getMessage(), e);
//        return ApiResponse.ofFailed(String.format("errorCode: %s, errorMessage: %s", e.getErrCode(), e.getMessage()));
        return ApiResponse.ofFailed(e.getMessage());
    }

    /**
     * 处理参数校验异常.
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public final ApiResponse<?> handleValidException(MethodArgumentNotValidException e) {
        String errorInfo = e.getMessage();
        if (!CollectionUtils.isEmpty(e.getBindingResult().getAllErrors())) {
            for (ObjectError error : e.getBindingResult().getAllErrors()) {
                log.error("{} 参数校验失败:{}", error.getObjectName(), error.getDefaultMessage());
                errorInfo = error.getDefaultMessage();
            }
        } else {
            log.error("参数校验失败:{}", e.getMessage());
        }
        log.error("RequestBody: {}", JSON.toJSONString(e.getBindingResult().getTarget()));
        return ApiResponse.ofFailed(errorInfo);
    }

    /**
     * 处理异常.
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public final ApiResponse<?> handleException(Exception e) {
        log.error("handleException--{}", e.getMessage(), e);

        // Throwable rootCause = Throwables.getRootCause(e);

        return ApiResponse.ofFailed("系统异常,请联系管理员!");
    }
}

 BusinessException

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * <p>业务异常</p>
 *
 * @author manhengwei
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class BusinessException extends RuntimeException {

    private final String errCode;

    public BusinessException(String message) {
        super(message);
        this.errCode = "";
    }

    public BusinessException(String errCode, String message) {
        super(message);
        this.errCode = errCode;
    }

    public BusinessException(String message, Throwable ex) {
        super(message, ex);
        this.errCode = "";
    }

    public BusinessException(String errCode, String message, Throwable ex) {
        super(message, ex);
        this.errCode = errCode;
    }
}

ApiResponse 

import lombok.Data;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * <ApiResponse>
 * @author manhengwei
 * @create 2021/5/31
 * @since 1.0.0
 * @date 2021-05-31 22:23
 */
@Data
public class ApiResponse<T> {
 
    private int code;
 
    private String message;
 
    private T data;
 
    private String traceId;
 
    public ApiResponse(int code, String message, T data) {
        setCode(code);
        setMessage(message);
        setData(data);
    }
 
    private Map<String, Object> ext = new HashMap<>();
 
    public static <T> ApiResponse<T> of(int code, String message, T data) {
        return new ApiResponse<>(code, message, data);
    }
 
    public static <T> ApiResponse<T> ofSuccess(T data) {
        return of(ApiStatus.SUCCESS, data);
    }
 
    public static <T> ApiResponse<T> ofFailed(T data) {
        return of(ApiStatus.FAILED, data);
    }
 
    public static <T> ApiResponse<T> ofFailed(String errorMsg, T data) {
        return of(ApiStatus.FAILED.getCode(),errorMsg, data);
    }
 
    public static <T> ApiResponse<T> ofFailed(String errorMsg) {
        return of(ApiStatus.FAILED.getCode(), errorMsg, null);
    }
 
    public static <T> ApiResponse<T> of(int code, String message) {
        return of(code, message, null);
    }
 
    public static <T> ApiResponse<T> of(ApiStatus apiStatus) {
        return of(apiStatus.getCode(), apiStatus.getMessage(), null);
    }
 
    public static <T> ApiResponse<T> of(int code, T data) {
        return of(code, null, data);
    }
 
    public static <T> ApiResponse<T> of(ApiStatus apiStatus, T data) {
        return of(apiStatus.getCode(), apiStatus.getMessage(), data);
    }
}

ApiStatus 

/**
 * 〈ApiStatus〉
 * @author manhengwei
 * @create 2021/5/31
 * @since 1.0.0
 * @date 2021-05-31 16:50
 */
public enum ApiStatus {
    SUCCESS(200, "success"),
    FAILED(0, "failed"),
    BAD_REQUEST(400, "Bad Request, Invalid param"),
    UNAUTHORIZED(401, "Unauthorized"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found"),
    LOCKED(423, "Locked"),
    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    SERVICE_UNAVAILABLE(503, "Service Unavailable"),
    SERVICE_EXCEPTION(50000, "请求异常,请检查参数后重试!");
 
    private final int code;
 
    private final String message;
 
    ApiStatus(int code, String message) {
        this.code = code;
        this.message = message;
    }
 
    public int getCode() {
        return code;
    }
 
    public String getMessage() {
        return message;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值