一、单个controller范围的异常处理

package com.xxx.secondboot.web;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.xxx.secondboot.exception.MyExceptionResponse;

import io.swagger.annotations.Api;

@Api("测试controllerAdvice和全局异常处理")
@RestController
@RequestMapping("/advice1")
public class AdviceController {

    @RequestMapping(value = "/test1", method = RequestMethod.GET)
    public String test1() {
        throw new RuntimeException("advice1 - exception1");
    }

    @RequestMapping(value = "/test2", method = RequestMethod.GET)
    public String test2() {
        throw new RuntimeException("advice1 - exception2");
    }

    @ExceptionHandler(RuntimeException.class)
    public MyExceptionResponse exceptionHandler() {
        MyExceptionResponse resp = new MyExceptionResponse();
        resp.setCode(300);
        resp.setMsg("exception-Handler");
        return resp;
    }

}

说明:

  • 在controller中加入被@ExceptionHandler修饰的类即可(在该注解中指定该方法需要处理的那些异常类)
  • 该异常处理方法只在当前的controller中起作用

二、全部controller范围内起作用的异常处理(全局异常处理)

1、全局异常处理类

package com.xxx.secondboot.web;

import javax.servlet.http.HttpServletResponse;

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.bind.annotation.RestController;

import com.xxx.secondboot.exception.MyExceptionResponse;
import com.xxx.secondboot.exception.MyRuntimeException;

//@ControllerAdvice(annotations=RestController.class)
//@ControllerAdvice(basePackages={"com.xxx","com.ooo"})
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    //    @ExceptionHandler(value={RuntimeException.class,MyRuntimeException.class})
    //    @ExceptionHandler//处理所有异常
    @ResponseBody //在返回自定义相应类的情况下必须有,这是@ControllerAdvice注解的规定
    public MyExceptionResponse exceptionHandler(RuntimeException e, HttpServletResponse response) {
        MyExceptionResponse resp = new MyExceptionResponse();
        resp.setCode(300);
        resp.setMsg("exception-Handler");
        //        response.setStatus(600);
        return resp;
    }
}

说明:

  • @ControllerAdvice是controller的一个辅助类,最常用的就是作为全局异常处理的切面类
  • @ControllerAdvice可以指定扫描范围
  • @ControllerAdvice约定了几种可行的返回值,如果是直接返回model类的话,需要使用@ResponseBody进行json转换
    • 返回String,表示跳到某个view
    • 返回modelAndView
    • 返回model + @ResponseBody

2、controller

package com.xxx.secondboot.web;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;

@Api("测试controllerAdvice和全局异常处理")
@RestController
@RequestMapping("/advice1")
public class AdviceController {

    @RequestMapping(value = "/test1", method = RequestMethod.GET)
    public String test1() {
        throw new RuntimeException("advice1 - exception1");
    }

    @RequestMapping(value = "/test2", method = RequestMethod.GET)
    public String test2() {
        throw new RuntimeException("advice1 - exception2");
    }

    //    @ExceptionHandler(RuntimeException.class)
    //    public MyExceptionResponse exceptionHandler() {
    //        MyExceptionResponse resp = new MyExceptionResponse();
    //        resp.setCode(300);
    //        resp.setMsg("exception-Handler");
    //        return resp;
    //    }

}

注意:

  • 同一个异常被局部范围异常处理器和全局范围异常处理器同时覆盖,会选择小范围的局部范围处理器
  • 同一个异常被小范围的异常类和大范围的异常处理器同时覆盖,会选择小范围的异常处理器

参考自:

  • http://jinnianshilongnian.iteye.com/blog/1866350 开涛的@ControllerAdvice(三个作用)
  • http://www.tuicool.com/articles/fA7nuii                springboot约定的异常处理体系
  • https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc springMVC异常处理体系
  • http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/ springMVC异常处理体系

【第二十三章】 springboot + 全局异常处理的更多相关文章

  1. 第二十三章 springboot + 全局异常处理

    一.单个controller范围的异常处理 package com.xxx.secondboot.web; import org.springframework.web.bind.annotation ...

  2. 《Linux命令行与shell脚本编程大全》 第二十三章 学习笔记

    第二十三章:使用数据库 MySQL数据库 MySQL客户端界面 mysql命令行参数 参数 描述 -A 禁用自动重新生成哈希表 -b 禁用 出错后的beep声 -B 不使用历史文件 -C 压缩客户端和 ...

  3. Gradle 1.12用户指南翻译——第二十三章. Java 插件

    其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Github上的地址: https://g ...

  4. “全栈2019”Java多线程第二十三章:活锁(Livelock)详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  5. “全栈2019”Java第二十三章:流程控制语句中决策语句switch上篇

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  6. springboot 全局异常处理

    springboot 全局异常处理 研究了半天springboot的全局异常处理,虽然还是需要再多整理一下,但是对于常见的404和500足以可以区分开,能够根据这两个异常分别处理 首先配置视图解析路径 ...

  7. 20190928 On Java8 第二十三章 注解

    第二十三章 注解 定义在 java.lang 包中的5种标准注解: @Override:表示当前的方法定义将覆盖基类的方法.如果你不小心拼写错误,或者方法签名被错误拼写的时候,编译器就会发出错误提示. ...

  8. Introduction to 3D Game Programming with DirectX 12 学习笔记之 --- 第二十三章:角色动画

    原文:Introduction to 3D Game Programming with DirectX 12 学习笔记之 --- 第二十三章:角色动画 学习目标 熟悉蒙皮动画的术语: 学习网格层级变换 ...

  9. 第二十三章 多项目集中权限管理及分布式会话——《跟我学Shiro》

    二十三章 多项目集中权限管理及分布式会话——<跟我学Shiro> 博客分类: 跟我学Shiro 跟我学Shiro  目录贴:跟我学Shiro目录贴 在做一些企业内部项目时或一些互联网后台时 ...

随机推荐

  1. 虚拟机VMware的网络设置出了问题会导致很多莫名的错误

    邪门地CentOS内软件安装失败问题:Xshell与虚拟机的各种连接失败:CentOS下eth0没显示ip地址. 这些原因竟然是一个,虚拟机VMware的网络设置出了问题.     恢复初始设置即可.

  2. No message body writer has been found for class com.alibaba.fastjson.JSONObject, ContentType: */*

    1:当使用 cxf 发布服务时,要求返回值类型为xml,或者json等 @Path("/searchProductByText") @GET @Produces({"ap ...

  3. POJ1789:Truck History(Prim算法)

    http://poj.org/problem?id=1789 Description Advanced Cargo Movement, Ltd. uses trucks of different ty ...

  4. [LeetCode] 252. Meeting Rooms_Easy tag: Sort

    Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si ...

  5. react native 淘宝镜像

    终端命令  open 打开 .npmrc 插入一行代码 registry=https://registry.npm.taobao.org

  6. recv函数返回值说明

    recv函数 int recv( SOCKET s, char FAR *buf, int len, int flags); 不论是客户还是服务器应用程序都用recv函数从TCP连接的另一端接收数据. ...

  7. vue框架(二)_vue环境搭建及创建项目

    1.node.js:概念介绍及安装 node.js:是一个基于chrome浏览器的v8引擎,可以运行javascript的环境(平台) 特性:异步IO模型 npm:是一个包管理器(工具),可以按装依赖 ...

  8. mongodb权限

    1.在无密码模式下添加账号 db.createUser( { user: "user", pwd: "pwd", roles: [ { role: " ...

  9. yii2 restful api --app接口编程

    转 http://www.yiichina.com/tutorial/1143yii2中restful url访问配置, 登陆接口access-token验证类 [ 2.0 版本 ] 登陆接口acce ...

  10. 网络流-最大流 Dinic模板

    #include <bits/stdc++.h> using namespace std; #define MP make_pair #define PB push_back #defin ...