1. 使用 @ControllerAdvice和@ExceptionHandler处理全局异常

1. 新建异常信息实体类

非必要的类,主要用于包装异常信息。

 package com.test.exception.myexception;

 public class ErrorResponse {
private String message;
private String errorTypeName; public ErrorResponse(Exception e) {
this(e.getClass().getName(), e.getMessage());
} public ErrorResponse(String errorTypeName, String message) {
this.errorTypeName = errorTypeName;
this.message = message;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public String getErrorTypeName() {
return errorTypeName;
} public void setErrorTypeName(String errorTypeName) {
this.errorTypeName = errorTypeName;
}
}

2. 自定义异常类型

package com.test.exception.myexception;

public class ReourceNotFoundException extends RuntimeException {
private String message; public ReourceNotFoundException() {
super();
} public ReourceNotFoundException(String message) {
super(message);
this.message = message;
} @Override
public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
}
}

3. 新建异常处理类

我们只需要在类上加上@ControllerAdvice注解这个类就成为了全局异常处理类,当然你也可以通过 assignableTypes指定特定的 Controller类,让异常处理类只处理特定类抛出的异常。

 package com.test.exception.handler;

 import com.test.exception.myexception.ErrorResponse;
import com.test.exception.myexception.ReourceNotFoundException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.ResponseStatusException; @ControllerAdvice(assignableTypes = {com.test.exception.controller.ExceptionController.class})
@ResponseBody
public class GlobalExceptionHandler {
ErrorResponse illegalArgumentResponse = new ErrorResponse(new IllegalArgumentException("参数错误!"));
ErrorResponse resourseNotFoundResponse = new ErrorResponse(new com.test.exception.myexception.ReourceNotFoundException("Sorry, the resourse not found!")); @ExceptionHandler(value = Exception.class)// 拦截所有异常, 这里只是为了演示,一般情况下一个方法特定处理一种异常
public ResponseEntity<ErrorResponse> exceptionHandler(Exception e) { if (e instanceof IllegalArgumentException) {
return ResponseEntity.status(400).body(illegalArgumentResponse);
} else if (e instanceof ReourceNotFoundException) {
return ResponseEntity.status(404).body(resourseNotFoundResponse);
}else if(e instanceof ResponseStatusException){
return ResponseEntity.status(502).body(resourseNotFoundResponse);
}
return null;
}
}

4. controller模拟抛出异常

 package com.test.exception.controller;

 import com.test.exception.myexception.ReourceNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException; @RestController
public class ExceptionController { @GetMapping("/illegalArgumentException")
public void throwException() {
throw new IllegalArgumentException();
} @GetMapping("/resourceNotFoundException")
public void throwException2() {
throw new ReourceNotFoundException(); } @GetMapping("/resourceNotFoundException2")
public void throwException3() {
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY,"The resource not found",new ReourceNotFoundException());
}
}

使用 Get 请求: http://localhost:8080/resourceNotFoundException

{"message":"Sorry, the resourse not found!","errorTypeName":"com.test.exception.myexception.ReourceNotFoundException"}

3. ResponseStatusException

研究 ResponseStatusException 我们先来看看,通过 ResponseStatus注解简单处理异常的方法(将异常映射为状态码)。

package com.test.exception.myexception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(code = HttpStatus.BAD_GATEWAY)
public class ReourceNotFoundException2 extends RuntimeException {
public ReourceNotFoundException2() {
} public ReourceNotFoundException2(String message) {
super(message);
}
}

这种通过 ResponseStatus注解简单处理异常的方法是的好处是比较简单,但是一般我们不会这样做,通过ResponseStatusException会更加方便,可以避免我们额外的异常类。

    @GetMapping("/resourceNotFoundException2")
public void throwException3() {
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY,"The resource not found",new ReourceNotFoundException());
}

ResponseStatusException 提供了三个构造方法:

    public ResponseStatusException(HttpStatus status) {
this(status, null, null);
} public ResponseStatusException(HttpStatus status, @Nullable String reason) {
this(status, reason, null);
} public ResponseStatusException(HttpStatus status, @Nullable String reason, @Nullable Throwable cause) {
super(null, cause);
Assert.notNull(status, "HttpStatus is required");
this.status = status;
this.reason = reason;
}

构造函数中的参数解释如下:

  • status : http status
  • reason :response 的消息内容
  • cause : 抛出的异常

@ControllerAdvice和@ExceptionHandler的更多相关文章

  1. @ControllerAdvice 和 @ExceptionHandler

    @ExceptionHandler的作用是把对不同异常处理抽取到不同的方法中. @ControllerAdvice的作用是把控制器中 @ExceptionHandler.@InitBinder.@Mo ...

  2. springmvc 全局的异常拦截处理 @ControllerAdvice注解 @ExceptionHandler

    第一步: Dispatcher前端控制器的源码中 默认的 private boolean throwExceptionIfNoHandlerFound = false;说明如果没有找到匹配的执行器,不 ...

  3. @ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常

    @ControllerAdvice 和 @ExceptionHandler 的区别 ExceptionHandler, 方法注解, 作用于 Controller 级别. ExceptionHandle ...

  4. Spring中通过java的@Valid注解和@ControllerAdvice实现全局异常处理。

    通过java原生的@Valid注解和spring的@ControllerAdvice和@ExceptionHandler实现全局异常处理的方法: controller中加入@Valid注解: @Req ...

  5. 统一异常处理@ControllerAdvice

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

  6. 从源码看全局异常处理器@ExceptionHandler&@ExceptionHandler的生效原理

    1.开头在前 日常开发中,几乎我们的项目都会用到异常处理器,我们通常会定制属于自己的异常处理器,来处理项目中大大小小.各种各样的异常.配置异常处理器目前最常用的方式应该是使用@ControllerAd ...

  7. SpringBoot RESTful 应用中的异常处理小结

    转载:https://segmentfault.com/a/1190000006749441 @ControllerAdvice 和 @ExceptionHandler 的区别 ExceptionHa ...

  8. 详细解说Java Spring的JavaConfig注解 【抄】

    抄自: http://www.techweb.com.cn/network/system/2016-01-05/2252188.shtml @RestController spring4为了更方便的支 ...

  9. Java Spring的 JavaConfig 注解

    序 传统spring一般都是基于xml配置的,不过后来新增了许多JavaConfig的注解.特别是springboot,基本都是清一色的java config,不了解一下,还真是不适应.这里备注一下. ...

随机推荐

  1. mapbox-gl空间分析插件turf.js使用介绍

    mapbox-gl能够方便地显示地图,做一些交互,但是缺少空间分析功能,比如绘制缓冲区.判断点和面相交等等. turf.js是一个丰富的用于浏览器和node.js空间分析库,官网 http://tur ...

  2. [Luogu P4145] 上帝造题的七分钟2 / 花神游历各国

    题目链接 题目简要:我们需要一个能支持区间内每一个数开方以及区间求和的数据结构. 解题思路:说道区间修改区间查询,第一个想到的当然就是分块线段树.数据范围要用long long.本来我是看到区间这两个 ...

  3. 014_STM32程序移植之_L298N电机驱动模块

    更改注意: STM32程序移植之L298N电机驱动模块 引脚连接图 STM32引脚 L298N引脚 功能 PA6 ENA 马达A的PWM PA7 ENB 马达B的PWM PA2 IN1 控制马达A P ...

  4. CF103D Time to Raid Cowavans 根号分治+离线

    题意: 给定序列 $a,m$ 次询问,每次询问给出 $t,k$. 求 $a_{t}+a_{t+k}+a_{t+2k}+.....a_{t+pk}$ 其中 $t+(p+1)k>n$ 题解: 这种跳 ...

  5. 独立看门狗 IWDG

    一,独立看门狗 二,独立看门狗的时钟源 独立看门狗拥有自己的时钟源,不依赖PLL时钟输出的分频信号,能够独立运行,这样子的好处就是PLL假如受到干扰, 导致运行异常,独立的看门狗还能正常地进行工作,如 ...

  6. leetcode解题报告(3):Search in Rotated Sorted Array

    描述 Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 m ...

  7. codeforces1213F tarjan缩点+拓扑排序

    题意 给定两个长度为n的排列p和q,构造一个字符串s满足\(s[p_i]<=s[p_{i+1}]\)和\(s[q_i]<=s[q_{i+1}]\),且满足字符串中不同字符的个数不少于k. ...

  8. scrapy框架之spider

    爬取流程 Spider类定义如何爬取指定的一个或多个网站,包括是否要跟进网页里的链接和如何提取网页内容中的数据. 爬取的过程是类似以下步骤的循环: 1.通过指定的初始URL初始化Request,并指定 ...

  9. Ubuntu 14.04 下安装redis后运行redis-cli 报出redis Connection refused错误【已解决】

    在运行redis-cli运行后爆出错误,看了网上的都没有用例如:改ip,注释bind 127.0.0.1,或者是先运行./redis-server redis.conf,都没有用 只需要: 找到red ...

  10. IDEA配置Hadoop开发环境&编译运行WordCount程序

    有关hadoop及java安装配置请见:https://www.cnblogs.com/lxc1910/p/11734477.html 1.新建Java project: 选择合适的jdk,如图所示: ...