文章目录
自定义异常类,继承RuntimeException全局异常处理响应结果枚举类测试自定义异常处理
自定义异常类,继承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();
}
}
全局异常处理
@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
;
}
}
响应结果枚举类
@NoArgsConstructor
@AllArgsConstructor
public enum ResultStatusEnum
{
SUCCESS(200, "请求成功!"),
PASSWORD_NOT_MATCHING(400, "密码错误");
@Getter
@Setter
private int code
;
@Getter
@Setter
private String message
;
}
测试自定义异常处理
@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错误");
}