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 JsonResponseBodyimplements 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;
}



