1异常
异常机制其实是帮助我们找到程序中的问题,异常的根类是 java.lang.Throwable ,其下有两个子类: java.lang.Error 与 java.lang.Exception ,平常所说的异常指 java.lang.Exception 。
Throwable体系:
Error:严重错误Error,无法通过处理的错误,只能事先避免,好比绝症。
Exception:表示异常,异常产生后程序员可以通过代码的方式纠正,使程序继续运行,是必须要处理的。好 比感冒、阑尾炎。
2 异常分类
我们平常说的异常就是指Exception,因为这类异常一旦出现,我们就要对代码进行更正,修复程序。
异常(Exception)的分类:
根据在编译时期还是运行时期去检查异常?
编译时期异常:checked异常。在编译时期,就会检查,如果没有处理异常,则编译失败。(如日期格式化异常)
运行时期异常:runtime异常。在运行时期,检查异常.在编译时期,运行异常不会编译器检测(不报错)。(如数学异 常)
2自定义异常
3 springboot整合自定义异常
3.1自定义异常类,继承RuntimeException
/**
* 自定制异常类
*
*/
@Getter
public class CustomException extends RuntimeException {
private int code;
private String message;
public CustomException(int code, String message) {
this.code = code;
this.message = message;
}
public CustomException(ResultStatusEnum resultStatusEnum) {
this.code = resultStatusEnum.getCode();
this.message = resultStatusEnum.getMessage();
}
}
3.2全局异常处理
/**
* 全局异常处理
*
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(CustomException.class)
public Map<String, Object> handleCustomException(CustomException customException) {
Map<String, Object> errorResultMap = new HashMap<>(16);
errorResultMap.put("code", customException.getCode());
errorResultMap.put("message", customException.getMessage());
return errorResultMap;
}
}
3.3响应结果枚举类
/**
* 响应结果状态枚举类
*
*/
@NoArgsConstructor
@AllArgsConstructor
public enum ResultStatusEnum {
/**
* 请求成功
*/
SUCCESS(200, "请求成功!"),
/**
* 密码错误
*/
PASSWORD_NOT_MATCHING(400, "密码错误");
@Getter
@Setter
private int code;
@Getter
@Setter
private String message;
}
3.4测试自定义异常处理
@GetMapping("/test/{id:\\d+}")
public UserDTO testError(@PathVariable("id") String userId) {
throw new CustomException(ResultStatusEnum.PASSWORD_NOT_MATCHING);
}
@GetMapping("/test2/{id:\\d+}")
public UserDTO testError2(@PathVariable("id") String userId) {
throw new CustomException(400, "这是400错误");
}