java response 异常抛出

原因:

如果没有自定义异常,那么http请求遇到错误时就会返回系统自带的异常,不利于问题的排查

{
    "timestamp": "2022-10-14T05:38:16.881+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "path": "/demo/10"
}

所以需要自定义异常,达到下面的结果

{
    "code": "401",
    "message": "错误类型1",
    "data": null
}

方案一:

自定义异常类,try,catch捕获异常(异常返回实体类,异常枚举值)

这种方式操作复杂,每次都需要捕获,大量重复代码

    @RequestMapping("/8")
    public CommonResponse testMpDb2(){
        try{
            CreditFicoData result = ficoService.findbyfname("提首付测四");
            String res = JSONObject.toJSONString(result);
            log.info(res);
            return CommonResponse.succeed(res);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return CommonResponse.failed(e.getMessage());
        }

    }

异常返回实体类:

@Getter
@Setter
public class CommonResponse {

    private String code;

    private String message;

    private Object data;

    public CommonResponse(String code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static CommonResponse getCommonResponse(String code,String message,Object data){
        return new CommonResponse(code,message,data);
    }

    public static CommonResponse succeed(Object data){
        return getCommonResponse(CodeEnum.Success.getCode(),CodeEnum.Success.getDesc(),data);
    }

    public static CommonResponse failed(String message){
        return getCommonResponse(CodeEnum.Fail.getCode(),message,null);
    }

    public static CommonResponse failed(String code,String message){
        return getCommonResponse(code,message,null);
    }
}

异常code枚举

public enum CodeEnum {

    Success("200","处理成功"),
    Fail("400","处理失败");

    private String code;
    private String desc;

    CodeEnum(String code,String desc){
        this.code = code;
        this.desc = desc;
    }

    public String getCode() {
        return code;
    }

    public String getDesc(){
        return desc;
    }
}

方案二:

为自定义异常类添加拦截器(异常返回实体类,异常枚举值,拦截器)

spring提供的统一的异常处理

不需要try,catch,自动包装返回的异常

拦截器:

@Slf4j
@ControllerAdvice
public class ExceptionHandle {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public CommonResponse handleException(Exception e){
        log.error("系统异常,{}",e.getMessage());
        return CommonResponse.failed(e.getMessage());
    }
}
    @RequestMapping("/9")
    public CommonResponse testMpDb3(){
        CreditFicoData result = ficoService.findbyfname("提首付测四");
        String res = JSONObject.toJSONString(result);
        log.info(res);
        int a = 1/0;
        return CommonResponse.succeed(res);
    }

方案三:

自定义返回的异常(异常返回实体类,异常枚举值,拦截器,自定义异常类,自定义异常枚举)

通过枚举类来定义异常,然后手动抛出异常,是常见的异常处理方式

自定义异常类:

@Data
public class BusinessException extends RuntimeException {

    private static final long serialVersionUID = 123456789L;

    private String errCode;

    private String errMessage;

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

    public BusinessException(ExceptionEnum e){
        super(e.getDesc());
        this.errCode = e.getCode();
        this.errMessage = e.getDesc();
    }
}

自定义异常枚举值

@Getter
public enum ExceptionEnum {

    Error_One("401","错误类型1"),
    Error_Two("402","错误类型2");

    private String code;

    private String desc;

    ExceptionEnum(String code,String desc){
        this.code = code;
        this.desc = desc;
    }
}

拦截器(添加新的异常拦截器)

@Slf4j
@ControllerAdvice
public class ExceptionHandle {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public CommonResponse handleException(Exception e){
        log.error("系统异常,{}",e.getMessage());
        return CommonResponse.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public CommonResponse handleownException(BusinessException e){
        log.error("系统异常,{}",e.getMessage());
        return CommonResponse.failed(e.getErrCode(),e.getErrMessage());
    }
}

手动抛出异常

@RequestMapping("/10")
public CommonResponse testMpDb4(){
    CreditFicoData result = ficoService.findbyfname("提首付测四");
    String res = JSONObject.toJSONString(result);
    log.info(res);
    if(2>1){
        throw new BusinessException(ExceptionEnum.Error_One);
    }
    return CommonResponse.succeed(res);
}

结果:

{
    "code": "401",
    "message": "错误类型1",
    "data": null
}

总结:

异常拦截器分为系统异常和手动抛出异常,return异常实体类自定义异常类解析抛出异常枚举类,异常返回实体类定义异常数据格式

posted @ 2022-10-14 13:54  yorkiiz  阅读(426)  评论(0编辑  收藏  举报