GVKun编程网logo

spring boot全局统一异常处理(spring boot 全局异常)

13

本文将带您了解关于springboot全局统一异常处理的新内容,同时我们还将为您解释springboot全局异常的相关知识,另外,我们还将为您提供关于18、SpringBoot中统一异常处理、spri

本文将带您了解关于spring boot全局统一异常处理的新内容,同时我们还将为您解释spring boot 全局异常的相关知识,另外,我们还将为您提供关于18、SpringBoot 中统一异常处理、spring boot 2 全局统一返回 RESTful 风格数据、统一异常处理、Spring Boot 中 Web 应用的统一异常处理、spring boot 中统一异常处理的实用信息。

本文目录一览:

spring boot全局统一异常处理(spring boot 全局异常)

spring boot全局统一异常处理(spring boot 全局异常)

自定义异常

 1 /**
 2  * 自定义异常
 3  * @author Holley
 4  * @create 2018-05-24 14:39
 5  **/
 6 public class SelectNoFindException extends RuntimeException{
 7     /**
 8      * 异常代码
 9      */
10     private Integer code;
11     /**
12      * 自定义错误信息
13      */
14     private String erromessage;
15 
16     public SelectNoFindException(String erromessage ,String message){
17         super(message);
18         this.erromessage = erromessage;
19     }
20 
21     public Integer getCode() {
22         return code;
23     }
24     public String getErromessage() {
25         return erromessage;
26     }
27     public void setCode(Integer code) {
28         this.code = code;
29     }
30     public void setErromessage(String erromessage) {
31         this.erromessage = erromessage;
32     }
33 
34 }
View Code

serviceimpl层代码

public List<Saler> listSalerContact(Long cid) {
        List<Saler> listSaler = null;
        try {
            listSaler = salerDAO.listSalerContact(cid);
        }catch (Exception e){
            e.printStackTrace();
            throw new  SelectNoFindException("获取订货商列表失败!!",e.getMessage());
        }
        return listSaler;
    }
View Code

全局统一异常处理代码

 1 /**
 2  * 全局统一异常处理
 3  * @author Holley
 4  * @create 2018-05-24 14:59
 5  **/
 6 @RestControllerAdvice
 7 public class GlobalExceptionHandler {
 8     private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
 9 
10     @ExceptionHandler(value = Exception.class)
11     public Response handler(Exception e){
12         Response r = new Response();
13         if (e instanceof SelectNoFindException){
14             SelectNoFindException selectNoFindException = (SelectNoFindException) e;
15             r.setMessage(selectNoFindException.getErromessage());
16             r.setCode(WhiteListConstant.RESPONSE_CODE_FAIL);
17             log.error(selectNoFindException.getMessage());
18             return r;
19         } else {
20             r.setCode(WhiteListConstant.RESPONSE_CODE_FAIL);
21             r.setMessage("系统错误");
22             log.error(e.getMessage());
23             return r;
24         }
25     }
26 }
View Code

 

18、SpringBoot 中统一异常处理

18、SpringBoot 中统一异常处理

1.1、定义统一返回结构

public class JsonResult {  
  
    private int code;  
  
    private String msg;  
  
    public JsonResult() {  
        this.code = 200;  
        this.msg = "成功";  
    }  
  
    public JsonResult(int code, String msg) {  
        this.code = code;  
        this.msg = msg;  
    }  
  
    public static JsonResult ofSuccess() {  
        return new JsonResult();  
    }  
  
    public static JsonResult ofError() {  
        return new JsonResult(500, "错误");  
    }  
  
    public static JsonResult ofError(int code, String msg) {  
        return new JsonResult(code, msg);  
    }  
	
    // 省略get/set等方法
}

1.2、处理异常

@ControllerAdvice  
@ResponseBody  
public class GlobalExceptionHandler {  
  
    @ExceptionHandler(MissingServletRequestParameterException.class)  
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)  
    public JsonResult handleHttpMessageNotReadableException(MissingServletRequestParameterException ex) {  
        System.out.println("缺少请求参数: " + ex.getMessage());  
        return JsonResult.ofError(404, "缺少必要的参数");  
    }  
  
    @ExceptionHandler(NullPointerException.class)  
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)  
    public JsonResult handleTypeMismatchException(NullPointerException ex) {  
        System.out.println("空指针异常: " + ex.getMessage());  
        return JsonResult.ofError(500, "空指针异常了");  
    }  

    // 建议写在GlobalExceptionHandler最下面,如果都没有找到,最后再拦截一下Exception异常,保证输出信息友好  
    @ExceptionHandler(Exception.class)  
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)  
    public JsonResult handleUnexpectedServer(Exception ex) {  
        return new JsonResult(500, "系统发生异常, 请联系管理员");  
    }  
}

1.3、处理自定义异常

public enum BusinessMsgEnum {  
  
  PARMETER_EXCEPTION(102, "参数异常!"),  
  
  SERVICE_TIME_OUT(103, "服务调用超时!"),  

  PARMETER_BIG_EXCEPTION(102, "输入的图片数量不能超过50张!"),  
  
  UNEXPECTED_EXCEPTION(500, "系统发生异常,请联系管理员!");  
  
  private int code;  
  
  private String msg;  
  
  BusinessMsgEnum(int code, String msg) {  
      this.code = code;  
      this.msg = msg;  
  }  
  
  // 省略set/get方法
}
public class BusinessErrorException extends RuntimeException {  
  
    private static final long serialVersionUID = -7480022450501760611L;  
  
    private int code;  

    private String message;  
  
    public BusinessErrorException(BusinessMsgEnum businessMsgEnum) {  
        this.code = businessMsgEnum.getCode();  
        this.message = businessMsgEnum.getMsg();  
    }  
  
    public int getCode() {  
        return code;  
    }  
  
    public void setCode(int code) {  
        this.code = code;  
    }  
  
    @Override  
    public String getMessage() {  
        return message;  
    }  
  
    public void setMessage(String message) {  
        this.message = message;  
    }  
}
@ExceptionHandler(BusinessErrorException.class)  
@ResponseStatus(value = HttpStatus.INTERNAL\_SERVER\_ERROR)  
public JsonResult handleBusinessError(BusinessErrorException ex) {  
    int code = ex.getCode();  
    String message = ex.getMessage();  
    return new JsonResult(code, message);  
}
// 测试Controller
@RestController  
@RequestMapping("/exception")  
public class ExceptionController {  
  
    @GetMapping("/test")  
    public JsonResult test(@RequestParam("name") String name, @RequestParam("pass") String pass) {  
        System.out.println(name + ", " + pass);  
        String s = null;  
        System.out.println(s.length());  
        return JsonResult.ofSuccess();  
    }  
}

spring boot 2 全局统一返回 RESTful 风格数据、统一异常处理

spring boot 2 全局统一返回 RESTful 风格数据、统一异常处理

全局统一返回 RESTful 风格数据,主要是实现 ResponseBodyAdvice 接口的方法,对返回值在输出之前进行修改。
使用注解 @RestControllerAdvice 拦截异常并统一处理。

开发环境:
IntelliJ IDEA 2019.2.2
jdk1.8
Spring Boot 2.2.2

1、创建一个 SpringBoot 项目,pom.xml 引用的依赖包如下

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

2、定义一个返回类

package com.example.response.entity;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.io.Serializable;

@Data
@NoArgsConstructor
@ToString
public class ResponseData<T> implements Serializable {
    /**
     * 状态码:0-成功,1-失败
     * */
    private int code;

    /**
     * 错误消息,如果成功可为空或SUCCESS
     * */
    private String msg;

    /**
     * 返回结果数据
     * */
    private T data;

    public static ResponseData success() {
        return success(null);
    }

    public static ResponseData success(Object data) {
        ResponseData result = new ResponseData();
        result.setCode(0);
        result.setMsg("SUCCESS");
        result.setData(data);
        return result;
    }

    public static ResponseData fail(String msg) {
        return fail(msg,null);
    }

    public static ResponseData fail(String msg, Object data) {
        ResponseData result = new ResponseData();
        result.setCode(1);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }
}

3、统一拦截接口返回数据

新建一个类 GlobalResponseHandler,用注解 @RestControllerAdvice,并且实现 ResponseBodyAdvice 接口的方法,其中方法 supports 可以判断哪些需要拦截,方法 beforeBodyWrite 可以对返回值在输出之前进行修改,从而实现返回统一的接口数据。

package com.example.response.config;

import com.alibaba.fastjson.JSON;
import com.example.response.entity.ResponseData;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 实现ResponseBodyAdvice接口,可以对返回值在输出之前进行修改
 */
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    //判断支持的类型
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 检查注解是否存在,存在则忽略拦截
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnorReponseAdvice.class)) {
            return false;
        }
        if (methodParameter.getMethod().isAnnotationPresent(IgnorReponseAdvice.class)) {
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 判断为null构建ResponseData对象进行返回
        if (o == null) {
            return ResponseData.success();
        }
        // 判断是ResponseData子类或其本身就返回Object o本身,因为有可能是接口返回时创建了ResponseData,这里避免再次封装
        if (o instanceof ResponseData) {
            return (ResponseData<Object>) o;
        }
        // String特殊处理,否则会抛异常
        if (o instanceof String) {
            return JSON.toJSON(ResponseData.success(o)).toString();
        }
        return ResponseData.success(o);
    }
}
新建自定义注解 IgnorReponseAdvice
package com.example.response.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnorReponseAdvice {
}

4、统一异常处理

package com.example.response.exception;
import com.example.response.entity.ResponseData;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseData exceptionHandler(Exception e) {
        e.printStackTrace();
        return ResponseData.fail("服务器异常:" + e.getMessage());
    }
}

5、新建一个测试用的实体类

package com.example.response.entity;

import lombok.Data;

@Data
public class User {
    private Long userId;
    private String userName;
    public User(Long userId, String userName){
        this.userId = userId;
        this.userName = userName;
    }
}

6、新建一个测试用的控制器类

package com.example.response.controller;

import com.example.response.config.IgnorReponseAdvice;
import com.example.response.entity.ResponseData;
import com.example.response.entity.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class DemoController {
    @GetMapping("user")
    public User user() {
        User u = new User(100L, "u1");
        return u;
    }

    @GetMapping("userList")
    public List<User> userList(){
        List<User> list = new ArrayList<User>();
        list.add(new User(100L, "u1"));
        list.add(new User(200L, "u2"));
        return list;
    }

    @GetMapping("test1")
    public String test1(){
        return "test1";
    }

    @GetMapping("test2")
    public ResponseData test2(){
        return ResponseData.success("test2");
    }

    @IgnorReponseAdvice
    @GetMapping("test3")
    public String test3() {
        return "test3";
    }

    @GetMapping("test4")
    public String test4() {
        Integer x = 1 / 0;
        return x.toString();
    }

    @GetMapping("test5")
    public String test5() throws Exception {
        throw new Exception("自定义异常信息");
    }
}

7、用 Postman 测试

(1) 请求 http://localhost:8080/user,返回

{
    "code": 0,
    "msg": "SUCCESS",
    "data": {
        "userId": 100,
        "userName": "u1"
    }
}

(2) 请求 http://localhost:8080/userList,返回

{
    "code": 0,
    "msg": "SUCCESS",
    "data": [
        {
            "userId": 100,
            "userName": "u1"
        },
        {
            "userId": 200,
            "userName": "u2"
        }
    ]
}

(3) 请求 http://localhost:8080/tes1,返回

{"msg":"SUCCESS","code":0,"data":"test1"}

(4) 请求 http://localhost:8080/test2,返回

{
    "code": 0,
    "msg": "SUCCESS",
    "data": "test2"
}

(5) 请求 http://localhost:8080/test3,返回

test3

(6) 请求 http://localhost:8080/test4,返回

{
    "code": 1,
    "msg": "服务器异常:/ by zero",
    "data": null
}

(7) 请求 http://localhost:8080/test5,返回

{
    "code": 1,
    "msg": "服务器异常:自定义异常信息",
    "data": null
}

  

参考文章:
https://blog.csdn.net/lrt890424/article/details/83624761
https://www.cnblogs.com/Purgeyao/p/11599810.html

Spring Boot 中 Web 应用的统一异常处理

Spring Boot 中 Web 应用的统一异常处理

我们在做 Web 应用的时候,请求处理过程中发生错误是非常常见的情况。Spring Boot 提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来展示异常内容。

选择一个之前实现过的 Web 应用(Chapter3-1-2)为基础,启动该应用,访问一个不存在的 URL,或是修改处理内容,直接抛出异常,如:

@RequestMapping("/hello")
public String hello() throws Exception {
    throw new Exception("发生错误");
}

此时,可以看到类似下面的报错页面,该页面就是 Spring Boot 提供的默认 error 映射页面。


alt = 默认的错误页面

统一异常处理

虽然,Spring Boot 中实现了默认的 error 映射,但是在实际应用中,上面你的错误页面对用户来说并不够友好,我们通常需要去实现我们自己的异常提示。

下面我们以之前的 Web 应用例子为基础(Chapter3-1-2),进行统一异常处理的改造。

  • 创建全局异常处理类:通过使用 @ControllerAdvice 定义统一的异常处理类,而不是在每个 Controller 中逐个定义。@ExceptionHandler 用来定义函数针对的异常类型,最后将 Exception 对象和请求 URL 映射到 error.html
@ControllerAdvice
class GlobalExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

}
  • 实现 error.html 页面展示:在 templates 目录下创建 error.html,将请求的 URL 和 Exception 对象的 message 输出。
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>统一异常处理</title>
</head>
<body>
    <h1>Error Handler</h1>
    <div th:text="${url}"></div>
    <div th:text="${exception.message}"></div>
</body>
</html>

启动该应用,访问:http://localhost:8080/hello,可以看到如下错误提示页面。


alt = 自定义的错误页面

通过实现上述内容之后,我们只需要在 Controller 中抛出 Exception,当然我们可能会有多种不同的 Exception。然后在 @ControllerAdvice 类中,根据抛出的具体 Exception 类型匹配 @ExceptionHandler 中配置的异常类型来匹配错误映射和处理。

返回 JSON 格式

在上述例子中,通过 @ControllerAdvice 统一定义不同 Exception 映射到不同错误处理页面。而当我们要实现 RESTful API 时,返回的错误是 JSON 格式的数据,而不是 HTML 页面,这时候我们也能轻松支持。

本质上,只需在 @ExceptionHandler 之后加入 @ResponseBody,就能让处理函数 return 的内容转换为 JSON 格式。

下面以一个具体示例来实现返回 JSON 格式的异常处理。

  • 创建统一的 JSON 返回对象,code:消息类型,message:消息内容,url:请求的 url,data:请求返回的数据
public class ErrorInfo<T> {

    public static final Integer OK = 0;
    public static final Integer ERROR = 100;

    private Integer code;
    private String message;
    private String url;
    private T data;

    // 省略getter和setter

}
  • 创建一个自定义异常,用来实验捕获该异常,并返回 json
public class MyException extends Exception {

    public MyException(String message) {
        super(message);
    }

}
  • Controller 中增加 json 映射,抛出 MyException 异常
@Controller
public class HelloController {

    @RequestMapping("/json")
    public String json() throws MyException {
        throw new MyException("发生错误2");
    }

}
  • MyException 异常创建对应的处理
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
        ErrorInfo<String> r = new ErrorInfo<>();
        r.setMessage(e.getMessage());
        r.setCode(ErrorInfo.ERROR);
        r.setData("Some Data");
        r.setUrl(req.getRequestURL().toString());
        return r;
    }

}
  • 启动应用,访问:http://localhost:8080/json,可以得到如下返回内容:
{
    code: 100data: "Some Data"message: "发生错误2"url: "http://localhost:8080/json"
}

至此,已完成在 Spring Boot 中创建统一的异常处理,实际实现还是依靠 Spring MVC 的注解,更多更深入的使用可参考 Spring MVC 的文档。

本文完整示例:chapter3-1-6

spring boot 中统一异常处理

spring boot 中统一异常处理

什么是异常?

通俗的说就是,让你感觉不爽的,阻碍你的事都算异常,也就是说不让我们程序正常运行的情况。

为什么要统一处理异常?

方便集中管理,集中定位问题

异常实例

举个例子,还用之前的学生信息那个案例,我们添加一个小于18岁的学生,调用接口,控制台报错如下:

 

 

 再看接口返回信息,如下图:

     

 

 

 

 

 添加失败                                                                                                添加成功

 

 

暂且先不说控制台报错,对比下,我们添加成功的接口信息返回情况,明显这给客户端调用我们程序的同学,有些不便,那么我们这里做下优化。

1、统一格式化输出json

 强迫症的我,这里有必要做下统一格式的输出,那么具体怎么做呢?

增加一个外层对象,用于包裹里面对象,具体代码示例如下:

package com.rongrong.springboot.demo.domain;

import lombok.Data;

/**
 * @description: 最外层对象
 * @author rongrong
 * @version 1.0
 * @date 2020/1/9 21:51
 */
@Data
public class Result<T> {
    private Integer code;
     String msg;
     T data;
}

针对成功、失败,定制统一的工具类,具体示例代码如下:

 com.rongrong.springboot.demo.utils;

 com.rongrong.springboot.demo.domain.Result;


 * @description: 统一格式化输出json
 *  1.0
 * @date 2020/1/9 21:55
 */
class ResultUtils {

    static Result success(Object obj){
        Result result = new Result();
        result.setCode(0);
        result.setMsg("success");
        result.setData(obj);
        return result;
    }

     Result success(){
        return success(null);
    }

     Result error(String msg){
        Result result =  Result();
        result.setCode(-1);
        result.setMsg(msg);
        //result.setMsg("unkNown error");
         result;
    }
}

接着我们需要对添加学生的接口进行改造,将我们封装好的工具类引入,达到统一输出的效果,具体代码如下:

 
     * 新增一个学生
     *
     * @return
     
    @PostMapping("/studentAdd")
    public Result<Student> sudentAdd(@Valid Student student,BindingResult bindingResult) {
        if(bindingResult.hasFieldErrors()){
            Result result = ResultUtils.error(bindingResult.getFieldError().getDefaultMessage());
            输出错误信息
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
             result;
        }
        student.setName(student.getName());
        student.setAge(student.getAge());
        student.setSex(student.getSex());
        student.setEmail(student.getEmail());
        Result result = ResultUtils.success(studentResponstory.save(student));
        保存和更新都用该方法
         result;
    }

我们调用接口服务,再来看接口返回,如下图:

     

 

 

 再来看下,明显舒服好多了。

2、多个异常情况的统一

现在我们实现这样一组功能,获取学生的年龄并判断,小于10岁,返回“应该上小学”,大于10岁且小于16岁,返回“应该上初中了”

我们需要在StudentService中写逻辑,供controller调用,具体代码如下:

   
     * 查询学生年龄
     *
     * @param id
     * @throws Exception
     */
    void getStudnetAge(Integer id) throws Exception {
        Student student = studentResponstory.findOne(id);
        Integer age = student.getAge();
        小于10岁,返回“应该上小学”,大于10岁且小于16岁,返回“应该上初中了”
        if (age <= 10) {
            throw new Exception("应该上小学");
        } else if (age > 10 && age < 16);
        }
    }

接着我们在StudentController中调用,具体代码示例如下:

   
     * 获取学生年龄
     * 
    @GetMapping("/students/getAge/{id}"void getAge(@PathVariable("id") Integer id)  Exception {
        studentService.getStudnetAge(id);
    }

数据库中学生的信息如下:

我们先来查询id为13、15、16的学生,查看接口返回信息如下:

    

     

 异常不一样,我们需要再次进行统一化管理了,输出统一格式化后的json。

3、使用 @ControllerAdvice 实现全局异常处理

显然我们需要把message中的信息及code组合外部对象,在包装内部返回data对象,这时需要我们使用 @ControllerAdvice 进行全局异常处理,配合@ExceptionHandle注解使用,@ExceptionHandle注解可以自动捕获controller层出现的指定类型异常,并对该异常进行相应的异常处理。

我们先来建立一个统一的异常类,继承RuntimeException,因为对于spring boot框架中,只有RuntimeException类的异常才会进行事务回滚,具体示例代码如下:

 com.rongrong.springboot.demo.exception;


 *  1.0
 * @description:
 * @date 2020/1/10 0:24
 class StudentException extends RuntimeException{
    code码
    错误信息
     String msg;

    public StudentException(Integer code,String msg) {
        this.code = code;
        this.msg = msg;
    }

    void setCode(Integer code) {
         code;
    }

     setMsg(String msg) {
         Integer getCode() {
         String getMsg() {
         msg;
    }
}

注意:此处必须用getSet方法,不能lombok插件,否则会报错,没有定义getSet方法。

接着我们再来编写全局异常处理,并针对异常类型做出判断,具体示例代码如下:

 com.rongrong.springboot.demo.handle;

 com.rongrong.springboot.demo.domain.Result;
 com.rongrong.springboot.demo.exception.StudentException;
 com.rongrong.springboot.demo.utils.ResultUtils;
 org.springframework.web.bind.annotation.ControllerAdvice;
 org.springframework.web.bind.annotation.ExceptionHandler;
 org.springframework.web.bind.annotation.ResponseBody;


 * @description: 全局异常处理
 *  1.0
 * @date 2020/1/10 0:17
 
@ControllerAdvice
 ExceptionHandle {

    @ResponseBody
    @ExceptionHandler(Exception. Result error(Exception e) {
        if(e instanceof StudentException){
            StudentException studentException=(StudentException)e;
             ResultUtils.error(studentException.getCode(),studentException.getMsg());
        }else {
            return ResultUtils.error(-1,"unkNown error!");
        }
    }
}

同样的,我们需要对StudentService中作出调整,修改为我们自定义的异常,具体示例代码如下:

  new StudentException(100,"应该上小学"new StudentException(101,"应该上初中了");
        }
    }

重新启动项目,再次调用查询学生年龄接口,查看返回结果如下所示证明成功。

   

 

 

 4、对code码的统一管理维护

很明显,现在两个报错对应两个code和msg,那么如果有多种code和msg对应的话这里感觉维护起来就很难了,所以我们要把它拿出来统一集中管理就好,这里使用枚举,来实现code和msg的映射。

具体示例代码如下:

 com.rongrong.springboot.demo.exceptionenum;

 1.0
 * @description:
 * @date 2020/1/9 23:11
 */

enum ResultEnum {

    UNKNow_ERROR(-1,1)">),HIGH_SCHOOL(10001,"应该上小学啦!");
     msg;
    }

    ResultEnum(Integer code,1)"> msg;
    }
}

接下来,需要我们在对StudentService中作出调整,修改为我们自定义的异常,传参为我们的枚举对象,具体示例代码如下:

小于10岁,返回“应该上小学”,大于10岁且小于16岁,返回“应该上初中了”,其他正常输出
         StudentException(ResultEnum.PRIMARY_SCHOOL);
        }  StudentException(ResultEnum.HIGH_SCHOOL);
        } StudentException(ResultEnum.SUCCESS);
        }
    }

接着在对,StudentException这个异常构造器,做下调整,具体代码如下:

 com.rongrong.springboot.demo.exceptionenum.ResultEnum;

 StudentException(ResultEnum resultEnum) {
         resultEnum.getCode();
         resultEnum.getMsg();
    }

     msg;
    }
}

最后,我们再来启动项目,调用下接口,返回如下信息,证明修改成功!

   

 5、单元测试

为了程序能够更好的运行,我们必须要做测试,所以要养成写完程序进行单元测试的好习惯。

那么在这里我们需要对Service、API进行测试。

5.1、对service进行单元测试

可以通过自定义创建类,来编写单元测试,也可以通过idea向导来创建,具体操作如下图所示:

具体示例代码如下:

 com.rongrong.springboot.demo.controller;

 com.rongrong.springboot.demo.domain.Student;
 com.rongrong.springboot.demo.responstory.StudentResponstory;
 org.junit.Assert;
 org.junit.Test;
 org.junit.runner.RunWith;
 org.springframework.beans.factory.annotation.Autowired;
 org.springframework.boot.test.context.SpringBoottest;
 org.springframework.test.context.junit4.springrunner;


 * @description: 对service进行单元测试
 *  1.0
 * @date 2020/1/10 20:52
 
@RunWith(springrunner.)
@SpringBoottest
 StudentControllerTest {

    @Autowired
    StudentResponstory studentResponstory;

    @Test
     sudentFindOne() {
        Student student = studentResponstory.findOne(13);
        Assert.assertEquals(new Integer(25figuremockmvc注解,配合mockmvcRequestBuilders、mockmvcResultMatchers来测试,具体示例代码如下:

 org.springframework.boot.test.autoconfigure.web.servlet.AutoConfiguremockmvc;
 org.springframework.test.context.junit4.springrunner;
 org.springframework.test.web.servlet.mockmvc;
 org.springframework.test.web.servlet.request.mockmvcRequestBuilders;
 org.springframework.test.web.servlet.result.mockmvcResultMatchers;


 * @description: 对API进行单元测试
 *  1.0
 * @date 2020/1/10 21:12
 )
@SpringBoottest
@AutoConfiguremockmvc
 StudentApiTest {


    @Autowired
    mockmvc mockmvc;

    @Test
    void testStudentApitest()  Exception {
        mockmvc.perform(mockmvcRequestBuilders.get("/students"))
                .andExpect(mockmvcResultMatchers.status().isOk())
                .andExpect(mockmvcResultMatchers.content().string("student"));
    }

}

运行测试,结果如下:

 

到此,spring boot 中统一异常处理,AutoConfiguremockmvc这个注解,感觉与powermock很像,其中各种APi,有兴趣的同学自己可以去尝试。

 

学习他人的优点,对比自己的不足!

总结

以上是小编为你收集整理的spring boot 中统一异常处理全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

关于spring boot全局统一异常处理spring boot 全局异常的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于18、SpringBoot 中统一异常处理、spring boot 2 全局统一返回 RESTful 风格数据、统一异常处理、Spring Boot 中 Web 应用的统一异常处理、spring boot 中统一异常处理的相关信息,请在本站寻找。

本文标签: