Spring boot异常统一处理方法:@ControllerAdvice注解的使用、全局异常捕获、自定义异常捕获

https://www.cnblogs.com/goloving/p/9142222.html

一、全局异常

1、首先创建异常处理包和类

2、使用@ControllerAdvice注解,全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获

package com.example.demo.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获
 */
@ResponseBody
@ControllerAdvice
public class MyControllerAdvice {
    @ExceptionHandler(value = Exception.class)
    public Map<String,Object> errorHandle(Exception e){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("code",-1);
        map.put("msg",e.getMessage());
        return map;
    }
}

  这上面有个需要注意的是要加上@ResponseBody注解,如果不加会怎么样呢,我们试下,报错:

javax.servlet.ServletException: Circular view path [hello]: would dispatch back to the current handler URL [/hello] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
    at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:209) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:147) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.31.jar:8.5.31]

  因为是个json的格式,所以必须要有@ResponseBody

3、测试:在hello里面造个异常

package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Value("${gwf.name}")
    private String msg;
    @RequestMapping("/hello")
    public String hello() {
        int num = 1/0;
        return this.msg;
    }
}

  结果:

二、自定义异常

1、首先创建自定义异常类:注意需要继承extends RuntimeException

package com.example.demo.exception;

public class BusinessException extends RuntimeException{
    private String code;
    private String msg;

    public BusinessException(String code, String msg) {
        super();
        this.code = code;
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

  这里介绍下idea自动生成get/set和构造函数的快捷键:alt + insert,然后选择getter和setter,constructor,自动生成get、set方法和构造函数

2、然后就是自定义异常捕获

package com.example.demo.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获
 */
@ResponseBody
@ControllerAdvice
public class MyControllerAdvice {
    @ExceptionHandler(value = Exception.class)
    public Map<String,Object> errorHandle(Exception e){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("code",-1);
        map.put("msg",e.getMessage());
        return map;
    }

    @ExceptionHandler(value = BusinessException.class)
    public Map<String,Object> errorHandle(BusinessException e){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("code",e.getCode());
        map.put("msg",e.getMsg());
        return map;
    }
}

3、最后我们测试下:抛出自定义异常

package com.example.demo;

import com.example.demo.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Value("${gwf.name}")
    private String msg;
    @RequestMapping("/hello")
    public String hello() {
        //int num = 1/0;
        throw new BusinessException("100","密码错误");
        //return this.msg;
    }
}

  结果:

原文地址:https://www.cnblogs.com/xiang--liu/p/11422368.html

时间: 2024-08-29 12:51:43

Spring boot异常统一处理方法:@ControllerAdvice注解的使用、全局异常捕获、自定义异常捕获的相关文章

spring mvc异常统一处理(ControllerAdvice注解)

@ControllerAdvice,是spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@ControllerAdvice的实现: Java代码   @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface ControllerAdvice { } 没什么特别之处,该注解使用@Component注解,这样的话当我们使用

Spring Boot 最核心的 25 个注解,都是干货!

Spring Boot 最核心的 25 个注解 1.@SpringBootApplication 这是 Spring Boot 最最最核心的注解,用在 Spring Boot 主类上,标识这是一个 Spring Boot 应用,用来开启 Spring Boot 的各项能力. 其实这个注解就是 @SpringBootConfiguration.@EnableAutoConfiguration.@ComponentScan 这三个注解的组合,也可以用这三个注解来代替 @SpringBootAppli

基于Spring Boot的统一异常处理设计

摘自:https://www.cnblogs.com/greyzeng/p/11733327.html Practitioner 需要不断努力,才能毫不费力 基于Spring Boot的统一异常处理设计 基于Spring Boot的统一异常处理设计 作者: Grey 原文地址:https://www.cnblogs.com/greyzeng/p/11733327.html Spring Boot中,支持RestControllerAdvice统一处理异常,在一个请求响应周期当中,如果Contro

自定义的Spring Boot starter如何设置自动配置注解

本文首发于个人网站:自定义的Spring Boot starter如何设置自动配置注解 在Spring Boot实战之定制自己的starter一文最后提到,触发Spring Boot的配置过程有两种方法: spring.factories:由Spring Boot触发探测classpath目录下的类,进行自动配置: @Enable:有时需要由starter的用户触发*查找自动配置文件的过程. 实战 接着上篇文章的例子,首先将spring.factories中的内容注释掉 #org.springf

Spring Boot 最核心的 25 个注解

1.@SpringBootApplication 这是 Spring Boot 最最最核心的注解,用在 Spring Boot 主类上,标识这是一个 Spring Boot 应用,用来开启 Spring Boot 的各项能力. 其实这个注解就是@SpringBootConfiguration.@EnableAutoConfiguration.@ComponentScan这三个注解的组合,也可以用这三个注解来代替 @SpringBootApplication 注解. 2.@EnableAutoCo

Spring boot异常统一处理方法:@ControllerAdvice注解的使用

1.首先创建异常处理包和类 2.使用@ControllerAdvice注解,全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获 package com.example.demo.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; impor

spring boot 2 统一异常处理

spring mvc 针对controller层异常统一处理非常简单,使用 @RestControllerAdvice 或 @RestControllerAdvice 注解就可以轻@RestControllerAdvice public class GatewayExceptionHandler { /*@ExceptionHandler(Exception.class) public JsonResult handleBusinessException(HttpServletRequest r

Spring Boot学习——统一异常处理

本随笔记录使用Spring Boot统一处理异常. 本文实例是从数据库中根据ID查询学生信息,要求学生的年龄在14--20岁之间.小于14岁,提示"你可能在上初中":大于20岁,提示"呢可能在上大学". 第一步,创建枚举类ResultEnum,用来管理异常信息 package *;//自己定义 public enum ResultEnum { UNKONW_ERROR(-1, "未知错误"), SUCCESS(0, "成功")

基于spring boot的统一异常处理

一.springboot的默认异常处理 Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来展示异常内容. 例如这里我们认为制造一个异常 @GetMapping(value = "/girls") public List<Girl> girlList() throws Exception{ throw new Exception("错误"); } 使用浏览器访问http:/