第一步:maven构建
springboot 引入web
第二步:准备实体类javabean
public class ErrorResponseEntity {
private int code;
private String message;
//get set conduct
}
第三步:准备一个自定义异常
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 4564124491192825748L;
private int code;
public CustomException() {
super();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public CustomException(String message, int code) {
super(message);
this.setCode(code);
}
}
第四步:配置文件-全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(CustomException.class)
public ErrorResponseEntity customExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
CustomException exception = (CustomException) e;
return new ErrorResponseEntity(exception.getCode(), exception.getMessage());
}
@ExceptionHandler(RuntimeException.class)
public ErrorResponseEntity runtimeExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
CustomException exception = (CustomException) e;
return new ErrorResponseEntity(400, exception.getMessage());
}
/**
* 通用的接口映射异常处理方
*/
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if (ex instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
return new ResponseEntity<>(new ErrorResponseEntity(status.value(), exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status);
}
if (ex instanceof MethodArgumentTypeMismatchException) {
MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex;
logger.error("参数转换失败,方法:" + exception.getParameter().getMethod().getName() + ",参数:" + exception.getName()
+ ",信息:" + exception.getLocalizedMessage());
return new ResponseEntity<>(new ErrorResponseEntity(status.value(), "参数转换失败"), status);
}
return new ResponseEntity<>(new ErrorResponseEntity(status.value(), "参数转换失败"), status);
}
}
第五步:写几个controller来试试看
@Controller
public class TestController {
@GetMapping("/test1")
public String test1() {
int i = 10 / 0;
return “test1”;
}
@GetMapping("/test2")
@ResponseBody
public Map<String, String> test2() {
Map<String, String> result = new HashMap<>(16);
// TODO 直接捕获所有代码块,然后在 cache
try {
int i = 10 / 0;
result.put("code", "200");
result.put("data", "具体返回的结果集");
} catch (Exception e) {
result.put("code", "500");
result.put("message", "请求错误");
}
return result;
}
@GetMapping("/test3")
@ResponseBody
public String test3(Integer num) {
if (num == null) {
throw new CustomException("num不能为空", 400);
}
if (num == 0) {
throw new CustomException("被除数不能为零", 888);
}
int i = 10 / num;
return "result:" + i;
}
}
结果展示