一、设置全局异常处理
测试类:
@RestController
public class TestController {
@GetMapping(value = "/v1/test_exception")
public Object hello(){
int i = 1/0;
return "Hello World!";
}
}
当启动项目访问http://localhost:8080/v1/test_exception时,页面会报500的错误。
添加一个全局异常处理类,捕获异常
@RestControllerAdvice
public class CustomExtHandler {
/**
* 全局异常类处理
* @param e
* @param request
* @return
*/
@ExceptionHandler(value = Exception.class)
Object handlerException(Exception e, HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
map.put("code", 100);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
}
}
再次访问上面地址时,页面就会显示json字符串,该异常已被捕获,可以进行相应的处理,使页面不会显示500的错误。
二、自定义异常及处理
创建一个自定义的异常类,该类继承RuntimeException
public class MwException extends RuntimeException{
private String code;
private String msg;
//get、set方法
public MwException(String code, String msg) {
this.code = code;
this.msg = msg;
}
}
创建测试方法,直接抛出异常
@GetMapping(value = "/v1/test_mw_exception")
public Object testMwException(){
throw new MwException("408", "mw exception");
}
1.创建捕获异常的处理方法,返回json字符串
@ExceptionHandler(value = MwException.class)
Object handlerException(MwException e, HttpServletRequest request){
//返回json数据
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("msg", e.getMsg());
map.put("url", request.getRequestURL());
return map;
}
访问http://localhost:8080/v1/test_mw_exception时,会返回json字符串。
2. 创建异常页面,当出现异常时,跳转至该页面
引入模版引擎:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在templates下创建error.html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
error
出异常了!!!
</body>
</html>
更改异常处理方法,使出现异常之后跳转至该异常页面:
@ExceptionHandler(value = MwException.class)
Object handlerException(MwException e, HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
return modelAndView;
}
当再次访问http://localhost:8080/test_mw_exception时,页面直接跳转至error.html。
本文介绍如何在SpringBoot中设置全局异常处理,包括捕获并处理各种异常,以及如何通过自定义异常来增强错误信息。同时,演示了如何通过返回JSON字符串或跳转到特定页面来优雅地处理异常。
1273

被折叠的 条评论
为什么被折叠?



