正常来说一个系统肯定有很多业务异常。而这些业务异常的信息如何返回给前台呈现给用户。比如用户的某些操作不被允许,需要给用户提示。

Spring 提供了@ControllerAdvice这个注解,这个注解可以实现全局异常处理,全局数据绑定,全局数据预处理,这里主要说下使用这个注解实现全局异常处理。

1.定义我们自己的业务异常ErrorCodeException

  1. package com.nijunyang.exception.exception;
  2.  
  3. /**
  4. * Description:
  5. * Created by nijunyang on 2019/12/20 9:36
  6. */
  7. public class ErrorCodeException extends RuntimeException {
  8.  
  9. private int code;
  10. /**
  11. * 用于填充资源文件中占位符
  12. */
  13. private Object[] args;
  14.  
  15. public ErrorCodeException(int code, Object... args) {
  16. this.code = code;
  17. this.args = args;
  18. }
  19.  
  20. public int getCode() {
  21. return code;
  22. }
  23.  
  24. public Object[] getArgs() {
  25. return args;
  26. }
  27.  
  28. }

2.编写统一异常处理器RestExceptionHandler,使用@ControllerAdvice注解修饰,在异常处理器编写针对某个异常的处理方法,使用@ExceptionHandler注解指向某个指定异常。当代码中抛了该异常就会进入此方法执行,从而返回我们处理后的信息给请求者。

3.资源文件放置提示信息,根据错误码去匹配提示信息。

  1. package com.nijunyang.exception.handler;
  2.  
  3. import com.nijunyang.exception.exception.ErrorCodeException;
  4. import com.nijunyang.exception.model.RestErrorResponse;
  5. import com.nijunyang.exception.model.Status;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.MessageSource;
  8. import org.springframework.http.HttpStatus;
  9. import org.springframework.http.ResponseEntity;
  10. import org.springframework.web.bind.annotation.ControllerAdvice;
  11. import org.springframework.web.bind.annotation.ExceptionHandler;
  12.  
  13. import javax.annotation.Resource;
  14. import java.io.File;
  15. import java.io.IOException;
  16. import java.util.Locale;
  17.  
  18. /**
  19. * Description: 控制层统一异常处理
  20. * Created by nijunyang on 2019/12/20 9:33
  21. */
  22. @ControllerAdvice
  23. public class RestExceptionHandler {
  24.  
  25. @Autowired
  26. private MessageSource messageSource;
  27.  
  28. //locale可以处理国际化资源文件,不同的语言
  29. @ExceptionHandler(value = ErrorCodeException.class)
  30. public final ResponseEntity<RestErrorResponse> handleBadRequestException(ErrorCodeException errorCodeException, Locale locale) {
  31. String message = messageSource.getMessage(String.valueOf(errorCodeException.getCode()), errorCodeException.getArgs(), locale);
  32. RestErrorResponse restErrorResponse = new RestErrorResponse(Status.FAILED, errorCodeException.getCode(), message);
  33. return new ResponseEntity<>(restErrorResponse, HttpStatus.OK);
  34. }
  35. }

4.配置文件指向资源文件位置(spring.messages.basename=xxx)

spring.messages.basename指向资源的前缀名字就行了,后面的国家语言标志不需要,Locale会根据系统的语言去识别,资源文件需要配置一个默认的(messages.properties),不然启动的时候可能无法正常注入资源,因为默认的是去加载不带国家语言标志的文件。

当然前缀随便配置什么都可以 只要再springboot的配置文件spring.messages.basename的路径配置正确就行,就像这样子也是可以的

5.控制层模拟异常抛出:

  1. package com.nijunyang.exception.controller;
  2.  
  3. import com.nijunyang.exception.exception.ErrorCodeException;
  4. import com.nijunyang.exception.model.ErrorCode;
  5. import org.springframework.http.ResponseEntity;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9.  
  10. /**
  11. * Description:
  12. * Created by nijunyang on 2019/12/20 9:58
  13. */
  14. @RestController
  15. @RequestMapping("/error")
  16. public class Controller {
  17.  
  18. @GetMapping("/file")
  19. public ResponseEntity test() {
  20. //模拟文件不存在
  21. String path = "a/b/c/d.txt";
  22. throw new ErrorCodeException(ErrorCode.FILE_DOES_NOT_EXIST_51001, path);
  23. }
  24. }

6.前台调用结果

z/b/c/d.txt就去填充了资源文件中的占位符

错误码:

  1. package com.nijunyang.exception.model;
  2.  
  3. /**
  4. * Description:
  5. * Created by nijunyang on 2020/1/20 20:28
  6. */
  7. public final class ErrorCode {
  8. public static int FILE_DOES_NOT_EXIST_51001 = 51001;
  9. }

结果状态:

  1. package com.nijunyang.exception.model;
  2.  
  3. /**
  4. * Description:
  5. * Created by nijunyang on 2019/12/20 10:21
  6. */
  7. public enum Status {
  8. SUCCESS,
  9. FAILED
  10. }

异常统一结果返回对象

  1. package com.nijunyang.exception.model;
  2.  
  3. /**
  4. * Description:
  5. * Created by nijunyang on 2019/12/20 9:38
  6. */
  7. public class RestErrorResponse {
  8.  
  9. private Status status;
  10. /**
  11. * 错误码
  12. */
  13. private Integer errorCode;
  14. /**
  15. * 错误信息
  16. */
  17. private String errorMsg;
  18.  
  19. public RestErrorResponse(Status status, Integer errorCode, String errorMsg) {
  20. this.errorCode = errorCode;
  21. this.errorMsg = errorMsg;
  22. this.status = status;
  23. }
  24.  
  25. public Integer getErrorCode() {
  26. return errorCode;
  27. }
  28.  
  29. public void setErrorCode(Integer errorCode) {
  30. this.errorCode = errorCode;
  31. }
  32.  
  33. public String getErrorMsg() {
  34. return errorMsg;
  35. }
  36.  
  37. public void setErrorMsg(String errorMsg) {
  38. this.errorMsg = errorMsg;
  39. }
  40.  
  41. public Status getStatus() {
  42. return status;
  43. }
  44.  
  45. }

pom文件依赖:springBoot版本是2.1.7.RELEASE

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-configuration-processor</artifactId>
  9. </dependency>
  10. </dependencies>

完整代码:https://github.com/bluedarkni/study.git  ---->springboot--->exception项目

@ControllerAdvice自定义异常统一处理的更多相关文章

  1. springBoot2.0 配置@ControllerAdvice 捕获异常统一处理

    一.前言 基于上一篇 springBoot2.0 配置shiro实现权限管理 这一篇配置 异常统一处理 二.新建文件夹:common,param 三.返回结果集对象 1.ResultData.java ...

  2. C#自定义异常 统一异常处理

    异常类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syst ...

  3. 统一异常处理@ControllerAdvice

    一.异常处理 有异常就必须处理,通常会在方法后面throws异常,或者是在方法内部进行try catch处理. 直接throws Exception 直接throws Exception,抛的异常太过 ...

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

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

  5. spring boot配置统一异常处理

    基于@ControllerAdvice的统一异常处理 >.这里ServerException是我自定义的异常,和普通Exception分开处理 >.这里的RequestResult是我自定 ...

  6. [转] Spring Boot中Web应用的统一异常处理

    [From] http://blog.didispace.com/springbootexception/ 我们在做Web应用的时候,请求处理过程中发生错误是非常常见的情况.Spring Boot提供 ...

  7. Java生鲜电商平台-统一异常处理及架构实战

    Java生鲜电商平台-统一异常处理及架构实战 补充说明:本文讲得比较细,所以篇幅较长. 请认真读完,希望读完后能对统一异常处理有一个清晰的认识. 背景 软件开发过程中,不可避免的是需要处理各种异常,就 ...

  8. SpringBoot接口 - 如何优雅的写Controller并统一异常处理?

    SpringBoot接口如何对异常进行统一封装,并统一返回呢?以上文的参数校验为例,如何优雅的将参数校验的错误信息统一处理并封装返回呢?@pdai 为什么要优雅的处理异常 如果我们不统一的处理异常,经 ...

  9. SpringBoot入门教程(十九)@ControllerAdvice+@ExceptionHandler全局捕获Controller异常

    在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@ModelAttribute,并应用到所有@Requ ...

随机推荐

  1. P1021 整数奇偶排序

    整数奇偶排序 题目出处:<信息学奥赛一本通>第二章上机练习6,略有改编 题目描述 告诉你包含 \(n\) 个数的数组 \(a\) ,你需要把他们按照"奇数排前面,偶数排后面:奇数 ...

  2. H3C 被动方式建立连接过程

  3. H3C 聚合链路负载分担原理

  4. dotnet 启动 JIT 多核心编译提升启动性能

    用2分钟提升十分之一的启动性能,通过在桌面程序启动 JIT 多核心编译提升启动性能 在 dotnet 可以通过让 JIT 进行多核心编译提升软件的启动性能,在默认托管的 ASP.NET 程序是开启的, ...

  5. 一个简单的Web服务器-支持Servlet请求

    上接 一个简单的Web服务器-支持静态资源请求,这个服务器可以处理静态资源的请求,那么如何处理Servlet请求的呢? 判断是否是Servlet请求 首先Web服务器需要判断当前请求是否是Servle ...

  6. 获取active nn并替换hue.ini

    namenodelists="nnip1,nnip2" nn1=$() nn2=$() nn1state=$(curl "http://$nn1:50070/jmx?qr ...

  7. C语言中的断言

    一.原型定义:void assert( int expression ); assert宏的原型定义在<assert.h>中,其作用是先计算表达式 expression ,如果expres ...

  8. HashMap、Hashtable、LinkedHashMap、TreeMap、ConcurrentHashMap的区别

    Map是Java最常用的集合类之一.它有很多实现类,我总结了几种常用的Map实现类,如下图所示.本篇文章重点总结几个Map实现类的特点和区别: 特点总结: 实现类 HashMap LinkedHash ...

  9. 【题解】ARC101F Robots and Exits(DP转格路+树状数组优化DP)

    [题解]ARC101F Robots and Exits(DP转格路+树状数组优化DP) 先删去所有只能进入一个洞的机器人,这对答案没有贡献 考虑一个机器人只能进入两个洞,且真正的限制条件是操作的前缀 ...

  10. selenium自动化测试入门 定位frame和iframe中的元素对象

    < frame> <iframe> 标签,浏览器会在标签中打开一个特定的页面窗口(框架),它在本窗口中嵌套进入一个网页,当用selenium定位页面元素的时候会遇到定位不到fr ...