首页 > 编程语言 >java response 异常抛出

java response 异常抛出

时间:2022-10-14 14:00:16浏览次数:46  
标签:code java String 抛出 response CommonResponse return 异常 public

原因:

如果没有自定义异常,那么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
}

标签:code,java,String,抛出,response,CommonResponse,return,异常,public
From: https://www.cnblogs.com/yorkiiz/p/16791408.html

相关文章

  • Java学习之路:流程控制
    2022-10-1110:58:41......
  • 打印三角形(java的for循环)
    publicclasstest{publicstaticvoidmain(String[]args){//输出n行的三角形intn=25;for(intj=0;j<n;j++){for(int......
  • java 在命令行下引用三方包编译并执行
    参考:https://blog.csdn.net/xuejiaodream/article/details/79161938方法:命令行进行.java当前目录,执行下面的命令编译java程序,$javac-cp".:fastjson-1.2.4.jar"HttpDemo......
  • JavaScript简单特效:页面背景颜色在线改变
    基于JavaScript以及canvas实现输入颜色预览以及背景颜色变为输入颜色值的效果。输入框中默认值为黑色,下方画布显示该颜色。通过输入新的颜色值后,点击【显示颜色】按钮,画......
  • java核心技术第四篇之JDBC第二篇
    01.JDBC连接池_连接池的概念:1).什么是连接池:对于多用户程序,为每个用户单独创建一个Connection,会使程序降低效率。这时我们可以创建一个"容器",这个容器中,先缓存一些Connect......
  • 前端成神之路-JavaScript高级第04天
    JavaScript高级第04天1.正则表达式概述1.1什么是正则表达式正则表达式(RegularExpression)是用于匹配字符串中字符组合的模式。在JavaScript中,正则表达式也是对象。正则表......
  • java学习记录1
    关于头文件:(pta)importjava.util.*(导入包)publicclassMain{publicstaticvoidmain(String[]args){}}输入:Scannerin(可以是任意字母)=newScanner(Syst......
  • java的参数传递
    编程语言都有方法(函数),方法里面有时候会有参数,我们称之为形式参数,主函数main函数里面也有参数,在主函数调用方法(函数)的时候,如果方法里面有形式参数,则需要在主函数将实际参数......
  • 图解Java设计模式之装饰者模式
    图解Java设计模式之装饰者模式​​星巴克咖啡订单项目(咖啡馆)​​​​方案1-解决星巴克咖啡订单项目​​​​方案1-解决星巴克咖啡订单问题分析​​​​方案2-解决星......
  • 图解Java设计模式之桥接模式
    图解Java设计模式之桥接模式​​手机操作问题​​​​传统方案解决手机操作问题​​​​传统方案解决手机操作问题分析​​​​桥接模式(Bridge)-基本介绍​​​​桥接模式解......