SpringBoot全局异常处理方式

 更新时间:2021年11月19日 14:50:30   作者:三毛村滴雪鱼粉  
这篇文章主要介绍了SpringBoot全局异常处理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

SpringBoot全局异常处理

为了让客户端能有一个更好的体验,当客户端发送请求到服务端发生错误时服务端应该明确告诉客户端错误信息。

在这里插入图片描述

SpringBoot内置的异常处理返回的界面太杂乱,不够友好。我们需要将异常信息做封装处理响应给前端。本文介绍的为将错误信息统一封装成如下格式json响应给前端。

{
	code:10001,
	message:xxxxx,
	request:GET url
}

自定义异常类

package com.lin.missyou.exception;
public class HttpException extends RuntimeException{
    protected Integer code;
    protected Integer httpStatusCode;
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public Integer getHttpStatusCode() {
        return httpStatusCode;
    }
    public void setHttpStatusCode(Integer httpStatusCode) {
        this.httpStatusCode = httpStatusCode;
    }
}
package com.lin.missyou.exception;
public class NotFoundException extends HttpException{
    public NotFoundException(int code){
        this.httpStatusCode = 404;
        this.code = code;
    }
}
package com.lin.missyou.exception;
public class ForbiddenException extends HttpException{
    public ForbiddenException(int code){
        this.httpStatusCode = 403;
        this.code = code;
    }
}

创建一个用于封装异常信息的类UnifyResponse

package com.lin.missyou.core;
public class UnifyResponse {
    private int code;
    private String message;
    private String request;
    public int getCode() {
        return code;
    }
    public String getMessage() {
        return message;
    }
    public String getRequest() {
        return request;
    }
    public UnifyResponse(int code, String message, String request) {
        this.code = code;
        this.message = message;
        this.request = request;
    }
}

将异常信息写在配置文件exception-code.properties里

lin.codes[10000] = 通用异常
lin.codes[10001] = 通用参数错误

自定义配置类管理配置文件

package com.lin.missyou.core.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@PropertySource(value="classpath:config/exception-code.properties")
@ConfigurationProperties(prefix = "lin")
@Component
public class ExceptionCodeConfiguration {
    private Map<Integer,String> codes = new HashMap<>();
    public Map<Integer, String> getCodes() {
        return codes;
    }
    public void setCodes(Map<Integer, String> codes) {
        this.codes = codes;
    }
    public String getMessage(int code) {
        String message = codes.get(code);
        return message;
    }
}

创建一个全局异常处理类GlobalExceptionAdvice,用@ControllerAdvice标明异常处理类。@ResponseStatus用于指定http状态码。

@ExceptionHandler标明异常处理器,传入参数指定当前函数要处理哪种类型的异常。Springboot会帮我们把这些异常信息传入到函数。第一个函数用于处理未知异常,不需要向前端提供详细的错误原因,只需提示统一的文本信息即可。

第二个函数用于处理已知异常,需要指明具体的错误原因,需要根据Exception传递过来的信息灵活的定制httpStatusCode。ResponseEntity可以自定义很多属性,包括可以设置httpheaders,httpbodys,httpStatus。

package com.lin.missyou.core;
import com.lin.missyou.core.config.ExceptionCodeConfiguration;
import com.lin.missyou.exception.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
@ControllerAdvice
public class GlobalExceptionAdvice {
    @Autowired
    ExceptionCodeConfiguration exceptionCodeConfiguration ;
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public UnifyResponse handleException(HttpServletRequest req,Exception e){
        String method = req.getMethod();
        String requestUrl = req.getRequestURI();
        System.out.println(e);
        UnifyResponse unifyResponse = new UnifyResponse(9999,"服务器错误",method+" "+requestUrl);
        return unifyResponse;
    }
    @ExceptionHandler(HttpException.class)
    public ResponseEntity<UnifyResponse> handleHttpException(HttpServletRequest req, HttpException e){
        String method = req.getMethod();
        String requestUrl = req.getRequestURI();
        System.out.println(e);
        UnifyResponse unifyResponse = new UnifyResponse(e.getCode(),exceptionCodeConfiguration.getMessage(e.getCode()),method+" "+requestUrl);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpStatus httpStatus = HttpStatus.resolve(e.getHttpStatusCode());
        ResponseEntity<UnifyResponse> responseEntity = new ResponseEntity(unifyResponse,httpHeaders,httpStatus);
        return responseEntity;
    }
    //参数校验
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public UnifyResponse handleBeanValidation(HttpServletRequest req, MethodArgumentNotValidException e){
        String method = req.getMethod();
        String requestUrl = req.getRequestURI();
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String message = formatAllErrorMessages(errors);
        return new UnifyResponse(10001,message,method+" "+requestUrl);
    }
    private String formatAllErrorMessages(List<ObjectError> errors){
        StringBuffer errorMsg = new StringBuffer();
        errors.forEach(error ->
                errorMsg.append(error.getDefaultMessage()).append(";")
        );
        return errorMsg.toString();
    }
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public UnifyResponse handleConstrainException(HttpServletRequest req, ConstraintViolationException e){
        String method = req.getMethod();
        String requestUrl = req.getRequestURI();
        String message = e.getMessage();
        return new UnifyResponse(10001,message,method+" "+requestUrl);
    }
}

在这里插入图片描述

响应信息可能会出现乱码现象,修改配置文件编码。在设置面板搜索File Encodings,Default encoding for properties files选择UTF-8,勾选Transparent native-to-ascii conversion

在这里插入图片描述

springboot全局异常处理——@ControllerAdvice+ExceptionHandler

一、全局捕获异常后,返回json给浏览器

项目结构:

在这里插入图片描述

1、自定义异常类 MyException.java

package com.gui.restful;
/**
 * 自定义异常类
 */
public class MyException extends RuntimeException{
    private String code;
    private String msg;
    public MyException(String code,String msg){
        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;
    }
}

2、控制器 MyController.java

package com.gui.restful;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
 * controller抛出异常
 */
@RestController
public class MyController {
    @RequestMapping("hello")
    public String hello() throws Exception{
        throw new MyException("101","系统异常");
    }
}

3、全局异常处理类 MyControllerAdvice

package com.gui.restful;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
 * 全局异常捕获处理
 */
@ControllerAdvice //controller增强器
public class MyControllerAdvice {
    @ResponseBody
    @ExceptionHandler(value=MyException.class) //处理的异常类型
    public Map myExceptionHandler(MyException e){
        Map<String,String> map=new HashMap<>();
        map.put("code",e.getCode());
        map.put("msg",e.getMsg());
        return map;
    }
}

4、运行结果

启动应用,访问 http://localhost:8080/hello,出现以下结果,说明自定义异常被成功拦截

在这里插入图片描述

二、全局捕获异常后,返回页面给浏览器

1、自定义异常类 MyException.java(同上)

2、控制器 MyController.java(同上)

3、全局异常处理类 MyControllerAdvice

package com.gui.restful;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
/**
 * 全局异常捕获处理
 */
@ControllerAdvice //controller增强器
public class MyControllerAdvice {
    @ExceptionHandler(value=MyException.class) //处理的异常类型
    public ModelAndView myExceptionHandler(MyException e){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("code",e.getCode());
        modelAndView.addObject("msg",e.getMsg());
        return modelAndView;
    }
}

4、页面渲染 error.ftl(用freemarker渲染)

pom.xml中引入freemarker依赖

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>

error.ftl

<!DOCTYPE>
<html>
<head>
<title>错误页面</title>
</head>
<body>
<h1>code:$[code]</h1>
<h1>msg:${msg}</h1>
</body>
</html>

5、运行结果

启动应用,访问 http://localhost:8080/hello,出现以下结果,说明自定义异常被成功拦截

在这里插入图片描述

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • springboot+redis分布式锁实现模拟抢单

    springboot+redis分布式锁实现模拟抢单

    这篇文章主要介绍了springboot+redis分布式锁实现模拟抢单,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-03-03
  • SpringBoot导入Druid运行失败问题

    SpringBoot导入Druid运行失败问题

    这篇文章主要介绍了SpringBoot导入Druid运行失败,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • mybatis-plus使用问题小结

    mybatis-plus使用问题小结

    这篇文章主要介绍了mybatis-plus使用问题汇总,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • 关于post请求内容无法重复获取的解决方法

    关于post请求内容无法重复获取的解决方法

    这篇文章主要介绍了关于post请求内容无法重复获取的解决方法,文中通过代码示例给大家介绍的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-03-03
  • 快速入门Java中的Lambda表达式

    快速入门Java中的Lambda表达式

    Lambda作为函数式编程中的基础部分,在其他编程语言中早就广为使用,但在Java领域中发展较慢,直到java8,才开始支持Lambda。网上关于Lambda的教程很多,今天小编给大家分享一篇快速入手Lambda的教程。
    2016-08-08
  • java操作json对象出现StackOverflow错误的问题及解决

    java操作json对象出现StackOverflow错误的问题及解决

    这篇文章主要介绍了java操作json对象出现StackOverflow错误的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • spring boot与kafka集成的简单实例

    spring boot与kafka集成的简单实例

    本篇文章主要介绍了spring boot与kafka集成的简单实例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • Spring基于XML实现Aop

    Spring基于XML实现Aop

    这篇文章主要介绍了Spring中基于xml的AOP的详细步骤,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-07-07
  • Java统计输入字符的英文字母、空格、数字和其它

    Java统计输入字符的英文字母、空格、数字和其它

    这篇文章主要介绍了Java统计输入字符的英文字母、空格、数字和其它,需要的朋友可以参考下
    2017-02-02
  • Spring Boot RestController接口输出到终端的操作代码

    Spring Boot RestController接口输出到终端的操作代码

    这篇文章主要介绍了Spring Boot RestController接口如何输出到终端,使用 HttpServletResponse 类,可以在使用curl执行 Spring Boot REST接口的同时,在控制台输出一些信息,给运维人员知道当前命令执行的状态,感兴趣的朋友跟随小编一起看看吧
    2023-09-09

最新评论