栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

idea中异常处理(全局异常处理)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

idea中异常处理(全局异常处理)

idea中异常处理(全局异常处理)
1)通过instanceof判断异常类型
2)通过设置mv.setView(new MappingJackson2JsonView())方式返回JSON数据;

4.3 使用@ControllerAdvice+@ExceptionHandler实现全局异常

@ControllerAdvice
public class GlobalExceptionResolver {

 @ExceptionHandler(value=RuntimeException.class)
 public ModelAndView handler(Exception e){
    ...
 }

}

4.4 响应封装类

  4.4.1 创建自定义异常类BusinessException

  BusinessException自定义异常类将继承RuntimeException异常,该异常类用于处理在程序代码运行过程所产生的运行时业务异常信息。

  4.4.2 创建响应枚举类JsonResponseStatus

  JsonResponseStatus响应枚举类用于自定义错误码。

  4.4.3 创建响应封装类JsonResponseBody

  JsonResponseBody响应封装类用于以JSON的形式统一输出错误信息。

案例1:SpringMVC自带的简单异常处理器
案例2:HandlerExceptionResovler接口实现全局异常
案例3:@ControllerAdvice+@ExceptionHandler实现全局异常
案例4:全局异常+响应封装类
示例1:在pom配置中不导入mysql的jar包,在mapper中的方法中throws Exception异常,再在全局异常中接收Exception类型异常并处理
示例2:所有services接口及实现类中的方法返回JsonResponseBody类型,并在其中处理业务抛出BusinessException业务异常
实例3:在Controller层中的方法中直接抛出BusinessException业务异常

附录一:?、T、K、V、E的区别?
? 表示不确定的java类型
T (type) 表示具体的一个java类型
K V (key value) 分别代表java键值中的Key Value
E (element) 代表Element

使用大写字母A,B,C,D…X,Y,Z定义的,就都是泛型,把T换成A也一样,这里T只是名字上的意义而已。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class BusinessException extends RuntimeException {
    private JsonResponseStatus jsonResponseStatus;
}
@Data
public class JsonResponseBody implements Serializable {

    private Integer total=0;
    private String msg="OK";
    private T data=null;
    private Integer code;

    public JsonResponseBody(){
        this.code=JsonResponseStatus.SUCCESS.getCode();
        this.msg=JsonResponseStatus.SUCCESS.getMsg();
    }

    public JsonResponseBody(JsonResponseStatus jsonResponseStatus){
        this.code=jsonResponseStatus.getCode();
        this.msg=jsonResponseStatus.getMsg();
    }

    public JsonResponseBody(T data){
        this.data=data;
        this.code=JsonResponseStatus.SUCCESS.getCode();
    }

    public JsonResponseBody(T data,Integer total){
        this.data=data;
        this.total=total;
        this.code=JsonResponseStatus.SUCCESS.getCode();
    }

    public JsonResponseBody(JsonResponseStatus jsonResponseStatus,T data){
        this.data=data;
        this.code=jsonResponseStatus.getCode();
        this.msg=jsonResponseStatus.getMsg();
    }
}

@Getter
@AllArgsConstructor
public enum JsonResponseStatus {

    SUCCESS(200,"OK"),
    ERROR(500,"服务器内部错误"),

    BOOK_NOTEMPTY(100101,"书本信息不能为空!")
    ;

    //错误代码
    private Integer code;
    //错误信息
    private String msg;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/685263.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号