自定义异常,返回异常信息

1 自定义异常

1.1 基础异常

RuntimeException 会被框架捕捉、抛出。

@Data
@EqualsAndHashCode(callSuper = false)
public class SpringBootPlusException extends RuntimeException{
    private Integer errorCode;
    private String message;

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

    public SpringBootPlusException(Integer errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
        this.message = message;
    }
}
1.2 继承异常
public class BusinessException extends SpringBootPlusException{
    public BusinessException(String message) {
        super(message);
    }
    public BusinessException(Integer errorCode, String message) {
        super(errorCode,message);
    }
}

2 返回异常信息

RuntimeException 的 super(message)只会返回异常的 message,不会返回异常的code,如果需要返回异常的code,需要单独处理。

2.1 异常处理块
@ControllerAdvice
@RestController
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {SpringBootPlusException.class})
    @ResponseStatus(HttpStatus.OK)
    public ApiResult springBootPlusExceptionHandler(SpringBootPlusException exception) {
        log.error("springBootPlusException:", exception);
        int errorCode;
        if (exception instanceof BusinessException) {
            errorCode = ApiCode.BUSINESS_EXCEPTION.getCode();
            if (Objects.nonNull(exception.getErrorCode())) {
                errorCode = exception.getErrorCode();
            }
        } else if (exception instanceof DaoException) {
            errorCode = ApiCode.DAO_EXCEPTION.getCode();
        } else {
            errorCode = ApiCode.SPRING_BOOT_PLUS_EXCEPTION.getCode();
        }
        return new ApiResult()
                .setCode(errorCode)
                .setMsg(exception.getMessage());
    }
}
2.2 返回对象

接口正常返回,也直接使用此对象返回。

@Data
@Accessors(chain = true)
@Builder
@AllArgsConstructor
public class ApiResult<T> implements Serializable {
    /**
     * 响应码
     */
    private int code;

    /**
     * 响应消息
     */
    private String msg;

    /**
     * 是否成功
     */
    private boolean success;

    /**
     * 响应数据
     */
    private T data;

    /**
     * 响应时间
     */
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date time  = new Date();

    public ApiResult() {

    }

    public static ApiResult result(boolean flag){
        if (flag){
            return ok();
        }
        return fail();
    }

    public static ApiResult result(ApiCode apiCode){
        return result(apiCode,null);
    }

    public static ApiResult result(ApiCode apiCode,Object data){
        return result(apiCode,null,data);
    }

    public static ApiResult result(ApiCode apiCode,String msg,Object data){
        boolean success = false;
        if (apiCode.getCode() == ApiCode.SUCCESS.getCode()){
            success = true;
        }
        String message = apiCode.getMsg();
        if (StringUtils.isNotBlank(msg)){
            message = msg;
        }
        return ApiResult.builder()
                .code(apiCode.getCode())
                .msg(message)
                .data(data)
                .success(success)
                .time(new Date())
                .build();
    }

    public static ApiResult ok(){
        return ok(null);
    }

    public static ApiResult ok(Object data){
        return result(ApiCode.SUCCESS,data);
    }

    public static ApiResult ok(Object data,String msg){
        return result(ApiCode.SUCCESS,msg,data);
    }

    public static ApiResult okMap(String key,Object value){
        Map<String,Object> map = new HashMap<>();
        map.put(key,value);
        return ok(map);
    }

    public static ApiResult fail(ApiCode apiCode){
        return result(apiCode,null);
    }

    public static ApiResult fail(String msg){
        return result(ApiCode.FAIL,msg,null);

    }

    public static ApiResult fail(ApiCode apiCode,Object data){
        if (ApiCode.SUCCESS == apiCode){
            throw new RuntimeException("失败结果状态码不能为" + ApiCode.SUCCESS.getCode());
        }
        return result(apiCode,data);

    }

    public static ApiResult fail(String key,Object value){
        Map<String,Object> map = new HashMap<>();
        map.put(key,value);
        return result(ApiCode.FAIL,map);
    }

    public static ApiResult fail() {
        return fail(ApiCode.FAIL);
    }
}
2.3 状态码枚举类
public enum ApiCode {

    SUCCESS(200, "operation success"),

    UNAUTHORIZED(401, "unauthorized"),

    NOT_PERMISSION(403, "not permission"),

    NOT_FOUND(404, "not found"),

    FAIL(500, "operation fail"),


    LOGIN_EXCEPTION(4000, "login exception"),


    SYSTEM_EXCEPTION(5000, "system exception"),

    PARAMETER_EXCEPTION(5001, "parameter exception"),

    PARAMETER_PARSE_EXCEPTION(5002, "parameter parse exception"),

    HTTP_MEDIA_TYPE_EXCEPTION(5003, "http_media type exception"),

    SPRING_BOOT_PLUS_EXCEPTION(5100, "spring boot plus exception"),

    BUSINESS_EXCEPTION(5101, "business exception"),

    DAO_EXCEPTION(5102, "data base exception"),

    VERIFICATION_CODE_EXCEPTION(5103, "verification code exception"),

    AUTHENTICATION_EXCEPTION(5104, "authentication exception"),

    UNAUTHENTICATED_EXCEPTION(5105, "unauthenticated exception"),

    UNAUTHORIZED_EXCEPTION(5106, "unauthorized exception"),

    UPLOAD_FORMAT_INCORRECT_EXCEPTION(5107, "Incorrect upload file format"),

    UPLOAD_EMPTY_FILE_EXCEPTION(5108, "No upload file or empty file exception"),

    UPLOAD_FAILED_EXCEPTION(5109, "Upload failed exception"),

    PRODUCT_MAPPING_FIELDS_REPEAT_EXCEPTION(5110, "Product mapping field is repeat"),

    DATA_VERIFIED_EXCEPTION(5111, "data verified exception"),

    DATA_INCOMPLETE_EXCEPTION(5112, "data incomplete exception"),

    DATA_INCONSISTENT_EXCEPTION(5113, "data inconsistent exception"),

    ;

    private final int code;
    private final String msg;

    ApiCode(final int code, final String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static ApiCode getApiCode(int code) {
        ApiCode[] ecs = ApiCode.values();
        for (ApiCode ec : ecs) {
            if (ec.getCode() == code) {
                return ec;
            }
        }
        return SUCCESS;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值