异常处理

Posted 116970u

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异常处理相关的知识,希望对你有一定的参考价值。

1.SpringBoot2.x配置全局异常实战
  讲解:服务端异常讲解和SpringBoot配置全局异常实战

  1、默认异常测试 int i = 1/0,不友好

  2、异常注解介绍
  @ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody
  若使用@ControllerAdvice,则需要添加 @ResponseBody
  //捕获全局异常,处理所有不可知的异常
  @ExceptionHandler(value=Exception.class)

代码示例:

ExceptionController.java:

 1 package net.xdclass.demo.controller;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.util.Date;
 6 import java.util.UUID;
 7 
 8 import javax.servlet.http.HttpServletRequest;
 9 
10 import net.xdclass.demo.domain.JsonData;
11 import net.xdclass.demo.domain.User;
12 
13 import org.springframework.beans.factory.annotation.Value;
14 import org.springframework.context.annotation.PropertySource;
15 import org.springframework.stereotype.Controller;
16 import org.springframework.web.bind.annotation.RequestMapping;
17 import org.springframework.web.bind.annotation.RequestParam;
18 import org.springframework.web.bind.annotation.ResponseBody;
19 import org.springframework.web.bind.annotation.RestController;
20 import org.springframework.web.multipart.MultipartFile;
21 
22 @RestController
23 public class ExceptionController {
24 
25     @RequestMapping(value = "/api/v1/test_ext")
26     public Object index() {
27         int i = 1/0;
28         return new User(11, "asddasf", "123456", new Date());
29     }
30 
31 }

CustomExtHandler.java:

 1 package net.xdclass.demo.domain;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 
 8 import org.slf4j.Logger;
 9 import org.slf4j.LoggerFactory;
10 import org.springframework.web.bind.annotation.ControllerAdvice;
11 import org.springframework.web.bind.annotation.ExceptionHandler;
12 import org.springframework.web.bind.annotation.ResponseBody;
13 import org.springframework.web.bind.annotation.RestControllerAdvice;
14 
15 
16 @RestControllerAdvice
17 public class CustomExtHandler {
18 
19     private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);
20 
21     
22     //捕获全局异常,处理所有不可知的异常
23     @ExceptionHandler(value=Exception.class)
24     //@ResponseBody
25     Object handleException(Exception e,HttpServletRequest request){
26         LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage()); 
27         Map<String, Object> map = new HashMap<>();
28             map.put("code", 100);
29             map.put("msg", e.getMessage());
30             map.put("url", request.getRequestURL());
31             return map;
32     }
33 }

访问:http://localhost:8083/api/v1/test_ext

在浏览器中查看后台返回的json数据:

 技术分享图片

2、SpringBoot2.x配置全局异常返回自定义页面
  简介:使用SpringBoot自定义异常和错误页面跳转实战

  1、返回自定义异常界面,需要引入thymeleaf依赖
  <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>


  2、resource目录下新建templates,并新建error.html
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("error.html");
  modelAndView.addObject("msg", e.getMessage());
  return modelAndView;

  代码示例1——进行页面跳转:

  MyException.java:

 1 package net.xdclass.demo.domain;
 2 
 3 /**
 4  * 功能描述:自定义异常类
 5  *
 6  */
 7 public class MyException extends RuntimeException {
 8 
 9     public MyException(String code, String msg) {
10         this.code = code;
11         this.msg = msg;
12     }
13 
14     private String code;
15     private String msg;
16     public String getCode() {
17         return code;
18     }
19     public void setCode(String code) {
20         this.code = code;
21     }
22     public String getMsg() {
23         return msg;
24     }
25     public void setMsg(String msg) {
26         this.msg = msg;
27     }
28 
29 }

  CustomExtHandler.java:

 1 package net.xdclass.demo.domain;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 
 8 import org.slf4j.Logger;
 9 import org.slf4j.LoggerFactory;
10 import org.springframework.web.bind.annotation.ExceptionHandler;
11 import org.springframework.web.bind.annotation.RestControllerAdvice;
12 import org.springframework.web.servlet.ModelAndView;
13 
14 
15 @RestControllerAdvice
16 public class CustomExtHandler {
17 
18     private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);
19 
20     
21     //捕获全局异常,处理所有不可知的异常
22     @ExceptionHandler(value=Exception.class)
23     Object handleException(Exception e,HttpServletRequest request){
24         LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage()); 
25         Map<String, Object> map = new HashMap<>();
26             map.put("code", 100);
27             map.put("msg", e.getMessage());
28             map.put("url", request.getRequestURL());
29             return map;
30     }
31     
32     
33 
34     /**
35      * 功能描述:处理自定义异常
36      * @return
37      */
38     @ExceptionHandler(value=MyException.class)
39     Object handleMyException(MyException e,HttpServletRequest request){
40         //进行页面跳转
41         ModelAndView modelAndView = new ModelAndView();
42         modelAndView.setViewName("error.html");
43         modelAndView.addObject("msg", e.getMessage());
44         return modelAndView;
45 
46     }
47      
48     
49 }

浏览器访问:http://localhost:8083/api/v1/myext

结果:

技术分享图片

  执行流程:

   先访问controller,controller抛出异常,被CustomExtHandler.java中的@RestControllerAdvice监听到,根据异常的种类找到对应的Handler。

  代码示例2——返回json数据:

 1     /**
 2      * 功能描述:处理自定义异常
 3      * @return
 4      */
 5     @ExceptionHandler(value=MyException.class)
 6     Object handleMyException(MyException e,HttpServletRequest request){
 7         
 8         //返回json数据,由前端去判断加载什么页面(通常用作前后端分离开发)
 9         Map<String, Object> map = new HashMap<>();
10         map.put("code", e.getCode());
11         map.put("msg", e.getMsg());
12         map.put("url", request.getRequestURL());
13         return map;

  结果:

  技术分享图片

  https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling


















以上是关于异常处理的主要内容,如果未能解决你的问题,请参考以下文章

使用片段中的处理程序时出现非法状态异常

Java异常处理机制

java 反射代码片段

java.util.MissingResourceException: Can't find bundle for base name init, locale zh_CN问题的处理(代码片段

使用实体框架迁移时 SQL Server 连接抛出异常 - 添加代码片段

片段中的Android致命异常