spring boot如何处理异步请求异常
springboot自定义错误页面
- 标签:
- spring-boot
方法一:Spring Boot 将所有的错误默认映射到/error, 实现ErrorController
@Controller
@RequestMapping(value = "error")
public class BaseErrorController implements ErrorController {
private static final Logger logger = LoggerFactory.getLogger(BaseErrorController.class);
@Override
public String getErrorPath() {
logger.info("出错啦!进入自定义错误控制器");
return "error/error";
}
@RequestMapping
public String error() {
return getErrorPath();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
方法二:添加自定义的错误页面
2.1 html静态页面:在resources/public/error/ 下定义
如添加404页面: resources/public/error/404.html页面,中文注意页面编码
2.2 模板引擎页面:在templates/error/下定义
如添加5xx页面: templates/error/5xx.ftl
注:templates/error/ 这个的优先级比较 resources/public/error/高
- 1
- 2
- 3
- 4
- 5
方法三:使用注解@ControllerAdvice
在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中。参考:@ControllerAdvice 文档
一、介绍
创建 MyControllerAdvice,并添加 @ControllerAdvice注解。
package com.sam.demo.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* controller 增强器
* @author sam
* @since 2017/7/17
*/
@ControllerAdvice
public class MyControllerAdvice {
/**
* 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {}
/**
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值
* @param model
*/
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("author", "Magical Sam");
}
/**
* 全局异常捕捉处理
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 100);
map.put("msg", ex.getMessage());
return map;
}
}
启动应用后,被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在 被 @RequestMapping 注解的方法上。
@ModelAttribute:在Model上设置的值,对于所有被 @RequestMapping 注解的方法中,都可以通过 ModelMap 获取,如下:
@RequestMapping("/home")
public String home(ModelMap modelMap) {
System.out.println(modelMap.get("author"));
}
//或者 通过@ModelAttribute获取
@RequestMapping("/home")
public String home(@ModelAttribute("author") String author) {
System.out.println(author);
}
@ExceptionHandler 拦截了异常,我们可以通过该注解实现自定义异常处理。其中,@ExceptionHandler 配置的 value 指定需要拦截的异常类型,上面拦截了 Exception.class 这种异常。
二、自定义异常处理(全局异常处理)
spring boot 默认情况下会映射到 /error 进行异常处理,但是提示并不十分友好,下面自定义异常处理,提供友好展示。
1、编写自定义异常类:
package com.sam.demo.custom;
/**
* @author sam
* @since 2017/7/17
*/
public class MyException extends RuntimeException {
public MyException(String code, String msg) {
this.code = code;
this.msg = msg;
}
private String code;
private String msg;
// getter & setter
}
注:spring 对于 RuntimeException 异常才会进行事务回滚。
2、编写全局异常处理类
创建 MyControllerAdvice.java,如下:
package com.sam.demo.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* controller 增强器
*
* @author sam
* @since 2017/7/17
*/
@ControllerAdvice
public class MyControllerAdvice {
/**
* 全局异常捕捉处理
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 100);
map.put("msg", ex.getMessage());
return map;
}
/**
* 拦截捕捉自定义异常 MyException.class
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = MyException.class)
public Map myErrorHandler(MyException ex) {
Map map = new HashMap();
map.put("code", ex.getCode());
map.put("msg", ex.getMsg());
return map;
}
}
3、controller中抛出异常进行测试。
@RequestMapping("/home")
public String home() throws Exception {
// throw new Exception("Sam 错误");
throw new MyException("101", "Sam 错误");
}
启动应用,访问:http://localhost:8080/home ,正常显示以下json内容,证明自定义异常已经成功被拦截。
{"msg":"Sam 错误","code":"101"}
* 如果不需要返回json数据,而要渲染某个页面模板返回给浏览器,那么MyControllerAdvice中可以这么实现:
@ExceptionHandler(value = MyException.class)
public ModelAndView myErrorHandler(MyException ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error");
modelAndView.addObject("code", ex.getCode());
modelAndView.addObject("msg", ex.getMsg());
return modelAndView;
}
在 templates 目录下,添加 error.ftl(这里使用freemarker) 进行渲染:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>错误页面</title>
</head>
<body>
<h1>${code}</h1>
<h1>${msg}</h1>
</body>
</html>
重启应用,http://localhost:8080/home 显示自定的错误页面内容。
补充:如果全部异常处理返回json,那么可以使用 @RestControllerAdvice 代替 @ControllerAdvice ,这样在方法上就可以不需要添加 @ResponseBody。
spring boot如何处理异步请求异常的更多相关文章
- spring boot / cloud (十二) 异常统一处理进阶
spring boot / cloud (十二) 异常统一处理进阶 前言 在spring boot / cloud (二) 规范响应格式以及统一异常处理这篇博客中已经提到了使用@ExceptionHa ...
- Spring boot 配置异步处理执行器
示例如下: 1. 新建Maven 项目 async-executor 2.pom.xml <project xmlns="http://maven.apache.org/POM/4.0 ...
- 【spring boot】spring boot 前台GET请求,传递时间类型的字符串,后台无法解析,报错:Failed to convert from type [java.lang.String] to type [java.util.Date]
spring boot 前台GET请求,传递时间类型的字符串,后台无法解析,报错:Failed to convert from type [java.lang.String] to type [jav ...
- Springboot 系列(七)Spring Boot web 开发之异常错误处理机制剖析
前言 相信大家在刚开始体验 Springboot 的时候一定会经常碰到这个页面,也就是访问一个不存在的页面的默认返回页面. 如果是其他客户端请求,如接口测试工具,会默认返回JSON数据. { &quo ...
- 二、spring boot 1.5.4 异常控制
spring boot 已经做了统一的异常处理,下面看看如何自定义处理异常 1.错误码页面映射 1.1静态页面 必须配置在 resources/static/error文件夹下,以错误码命名 下面是4 ...
- Spring Boot Async异步执行
异步调用就是不用等待结果的返回就执行后面的逻辑,同步调用则需要等带结果再执行后面的逻辑. 通常我们使用异步操作都会去创建一个线程执行一段逻辑,然后把这个线程丢到线程池中去执行,代码如下: Execut ...
- Spring Boot @ControllerAdvice 处理全局异常,返回固定格式Json
需求 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0, "data": {}, "msg": ...
- 踩坑记录:spring boot的POST请求数据注入不了的问题
概述: 今天在使用spring boot框架的时候,踩了一个坑,是关于control层request body依赖注入的问题的,内容如下: 进过: 由于目前公司采用的系统架构,要求把springboo ...
- Spring boot处理OPTIONS请求
一.现象从fetch说起,用fetch构造一个POST请求. fetch('http://127.0.0.1:8000/api/login', { method: "POST", ...
随机推荐
- jQyery简史和下载引用方法
1.jQuery简介 jQuery是一个快速,小型且功能丰富的JavaScript库.借助易于使用的API(可在多种浏览器中使用),使HTML文档的遍历和操作,事件处理,动画和Ajax等事情变得更加简 ...
- C++标准库中的std::endl究竟做了什么?
先抓出std::endl的源代码: /** * @file ostream * @brief Write a newline and flush the stream. * * This m ...
- 深入js系列-环境
javascript运行环境 js如果只在引擎中运行,它会严格遵循并且可以预测的,但是js几乎都在宿主环境中运行,浏览器或者Node环境 ECMAScript中的Annex B 介绍了浏览器兼容性问题 ...
- Generator生成器函数执行过程的理解
一个最基本的Generator函数格式如下,函数体内部要使用yield修饰符则必须在函数名前加上*号 ; function *testYield(x){ console.log('before yie ...
- Android Studio 之 控件基础知识
1. TextView 和 EditText 控件常用属性 android:layout_width="match_parent" 宽度与父控件一样宽 android:layou ...
- java基础之 数据类型 & 值传递 引用传递 & String & 四种引用类型
一.Java数据类型 分为基本数据类型与引用数据类型 基本数据类型: byte:Java中最小的数据类型,在内存中占1个字节(8 bit),取值范围-128~127,默认值0 short:短整型,2个 ...
- IRQL
IRQL是Interrupt ReQuest Level,中断请求级别. 一个由windows虚拟出来的概念,划分在windows下中断的优先级,这里中断包括了硬中断和软中断,硬中断是由硬件产生,而软 ...
- c++primer(第五版) 阅读笔记
快速阅读一遍c++ primer,复习c++ 1.本书代码:http://www.informit.com/store/c-plus-plus-primer-9780321714114 2.本书结构:
- leetcode-19:给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * Lis ...
- IE 浏览器设置 打开新的选项卡而不是弹出窗口
首先打开IE的页面 找到工具 —点击Internet选项