先上代码,不捕获异常和手动捕获异常处理:
@GetMapping("/error1") public String error1() { int i = 10 / 0; return "test1"; } @ResponseBody @GetMapping("/error2") public Map<String, String> error2() { Map<String, String> result = new HashMap<>(16); try{ int i = 10 / 0; result.put("code", "200"); result.put("data", "具体返回的结果集"); } catch (Exception e) { result.put("code", "500"); result.put("message", "请求错误"); } return result; }
其中的各种问题就不再多说了,由于各种问题,因此需要对异常进行统一捕获
1、导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2、自定义异常类
package com.example.demo.entity;
import lombok.Data;
@Data
public class ErrorResponse {
private int code;
private String message;
public ErrorResponse(int code, String message) {
this.code = code;
this.message = message;
}
public ErrorResponse() {
}
public ErrorResponse OK(String message){
this.code = 200;
this.message = message;
return this;
}
public void OK(){
this.code = 200;
this.message = "";
}
}
3、定义异常模板
package com.example.demo.entity; import lombok.Data; @Data public class ErrorResponse { private int code; private String message; public ErrorResponse(int code, String message) { this.code = code; this.message = message; } }
4、异常拦截器
此步时重点,需要特殊说明一下,
@ControllerAdvice 捕获 Controller 层抛出的异常,如果添加 @ResponseBody 返回信息则为JSON 格式。
@RestControllerAdvice 相当于 @ControllerAdvice 与 @ResponseBody 的结合体。
@ExceptionHandler 统一处理一种类的异常,减少代码重复率,降低复杂度。 创建一个 GlobalExceptionHandler 类,并添加上 @RestControllerAdvice 注解就可以定义出异常通知类了,然后在定义的方法中添加上 @ExceptionHandler 即可实现异常的捕捉…
package com.example.demo.utils; import com.example.demo.entity.ErrorResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.lang.Nullable; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @RestControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(LclException.class) public ErrorResponse lclExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response){ response.setStatus(HttpStatus.BAD_REQUEST.value()); LclException exception = (LclException) e; return new ErrorResponse(exception.getCode(),exception.getMessage()); } @ExceptionHandler(RuntimeException.class) public ErrorResponse runtimeExcetionHandler(HttpServletRequest request, final Exception e,HttpServletResponse response){ response.setStatus(HttpStatus.BAD_REQUEST.value()); RuntimeException exception = (RuntimeException) e; return new ErrorResponse(400,exception.getMessage()); } @Override protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { if(ex instanceof MethodArgumentNotValidException){ MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex; return new ResponseEntity<>(new ErrorResponse(status.value(),exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status); } if(ex instanceof MethodArgumentTypeMismatchException){ MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex; return new ResponseEntity<>(new ErrorResponse(status.value(),"参数转换异常"),status); } return new ResponseEntity<>(new ErrorResponse(status.value(), "参数转换异常"), status); } }
5、测试类
@ResponseBody
@GetMapping("/error3")
public ErrorResponse error3(Integer num) throws LclException{
if(num == null){
throw new LclException(12345,"num不允许为空");
}
int i = 10/num;
return (new ErrorResponse()).OK(i+"");
}
6、测试