springboot(4) 项目中全局异常的处理
2017-07-12 18:44
507 查看
如今的项目,大多都会进行全局异常的处理,下面介绍如何自定义全局异常处理。
1.在项目下新建一个包,编写异常处理类
package com.example.demo.exception;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public String exceptionHandler(HttpServletRequest req, Exception e){
String requestURI = req.getRequestURI();
String return_s=requestURI+" is error :"+e.getMessage();
return return_s;
}
}
解析:上述类上面引用 @ControllerAdvice注解,注解从字面上理解为控制器增强,最大的用处就是用来定义全局异常处理类,方法上方引用注解 @ExceptionHandler(value = Exception.class),表示处理的异常为哪些,方法中为你自己定义的处理方式,本人将含有异常的方法名和错误信息以JSON的格式返回。
2.调用其他含有异常的的方法,例如
@GetMapping("/testExceptionHandler")
public void testExceptionHandler(){
int a= 100/0;
System.out.println(a);
}
访问: http://localhost:8080/first/testExceptionHandler,返回结果如下:
/first/testExceptionHandler is error :/ by zero
至此,全局异常就到此结束,下一篇将讲述与数据库层面的交互。
1.在项目下新建一个包,编写异常处理类
package com.example.demo.exception;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public String exceptionHandler(HttpServletRequest req, Exception e){
String requestURI = req.getRequestURI();
String return_s=requestURI+" is error :"+e.getMessage();
return return_s;
}
}
解析:上述类上面引用 @ControllerAdvice注解,注解从字面上理解为控制器增强,最大的用处就是用来定义全局异常处理类,方法上方引用注解 @ExceptionHandler(value = Exception.class),表示处理的异常为哪些,方法中为你自己定义的处理方式,本人将含有异常的方法名和错误信息以JSON的格式返回。
2.调用其他含有异常的的方法,例如
@GetMapping("/testExceptionHandler")
public void testExceptionHandler(){
int a= 100/0;
System.out.println(a);
}
访问: http://localhost:8080/first/testExceptionHandler,返回结果如下:
/first/testExceptionHandler is error :/ by zero
至此,全局异常就到此结束,下一篇将讲述与数据库层面的交互。
相关文章推荐
- springboot学习-全局异常处理
- SpringBoot全局异常处理
- 轻松实现SpringBoot项目异常全局处理
- 项目中全局异常处理
- SpringBoot入门-7(全局异常处理)
- Android客户端项目全局异常处理和服务器数据保存
- 项目全局异常处理
- springboot全局异常处理
- 框架 day89 涛涛商城项目(补)-activeMQ应用,及springMVC全局异常处理
- asp.net全局异常处理
- n层结构的J2EE项目中的异常处理之二 转载
- J2EE项目中的异常处理 转载
- n层结构的J2EE项目中的异常处理之四 转载
- n层结构的J2EE项目中的异常处理之三 转载
- 项目开发-ASP.NET项目开发中的异常处理
- N层结构的J2EE项目中的异常处理之二 转载
- N层结构的J2EE项目中的异常处理之一 转载
- ASP.NET 全局异常处理
- [ZZ]重载new/delete 运算符与 重载全局异常处理
- 没头没尾--项目开发笔记:异常处理与日志记录代码自动生成(工具能生成多少代码!?续一)