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;

/**
 * 

异常处理

* * @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;

/**
 * 

业务异常

* * @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;
 
/**
 * 
 * @author manhengwei
 * @create 2021/5/31
 * @since 1.0.0
 * @date 2021-05-31 22:23
 */
@Data
public class ApiResponse {
 
    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 ext = new HashMap<>();
 
    public static  ApiResponse of(int code, String message, T data) {
        return new ApiResponse<>(code, message, data);
    }
 
    public static  ApiResponse ofSuccess(T data) {
        return of(ApiStatus.SUCCESS, data);
    }
 
    public static  ApiResponse ofFailed(T data) {
        return of(ApiStatus.FAILED, data);
    }
 
    public static  ApiResponse ofFailed(String errorMsg, T data) {
        return of(ApiStatus.FAILED.getCode(),errorMsg, data);
    }
 
    public static  ApiResponse ofFailed(String errorMsg) {
        return of(ApiStatus.FAILED.getCode(), errorMsg, null);
    }
 
    public static  ApiResponse of(int code, String message) {
        return of(code, message, null);
    }
 
    public static  ApiResponse of(ApiStatus apiStatus) {
        return of(apiStatus.getCode(), apiStatus.getMessage(), null);
    }
 
    public static  ApiResponse of(int code, T data) {
        return of(code, null, data);
    }
 
    public static  ApiResponse 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;
    }
}

你可能感兴趣的:(java,开发语言)