先上代码,不捕获异常和手动捕获异常处理:

@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、测试

  

最新文章

  1. C#中js文本提示
  2. SSAS:概念梳理
  3. 八、java集合类
  4. Postman接口测试初探
  5. Cloud_panel
  6. python--for循环
  7. 网络流相关(拓扑)CodeForces 269C:Flawed Flow
  8. 团队作业4——第一次项目冲刺(Alpha版本)1st day
  9. 《C++ Primer》学习笔记:迭代器介绍
  10. CentOs~程序部署那些事
  11. 【H5 音乐播放实例】第一节 音乐详情页制作(1)
  12. 自己动手实现java数据结构(一) 向量
  13. ettercap中间人攻击--参数介绍
  14. 9 tips to improve spoken english
  15. c# 检查目录,当指定目录不存在时建立目录
  16. 秘钥登录服务器执行shell脚本
  17. 0xWS2812 STM32 driver for WS2812(B) RGB LEDs
  18. 在 Windows Server 2008 中部署带 SignalR 的网站出错
  19. Eclipse js报错问题解决办法
  20. 移动端 实现ul横向滚动条

热门文章

  1. 我终于看懂了HBase,太不容易了...
  2. Java实现 LeetCode 659 分割数组为连续子序列 (哈希)
  3. Java中多态举例说明
  4. java实现第六届蓝桥杯垒骰子
  5. mysql数据库运维方案
  6. hackrf 输出功率测试
  7. Python快速入门文档
  8. Tomcat的8080端口被占用无法启动Tomcat怎么办?
  9. Python脚本批量修改服务器密码
  10. Mybatis反射修改SQL值