springboot2.0系列教程springboot框架添加全局异常处理(代码片段)

mrbeany mrbeany     2022-12-05     383

关键词:

Hello大家好,本章我们添加全局异常处理。另求各路大神指点,感谢

一:为什么需要定义全局异常

在互联网时代,我们所开发的应用大多是直面用户的,程序中的任何一点小疏忽都可能导致用户的流失,而程序出现异常往往又是不可避免的,所以我们需要对异常进行捕获,然后给予相应的处理,来减少程序异常对用户体验的影响

二:添加业务类异常

在前面说过的ret文件夹下创建ServiceException

package com.example.demo.core.ret;

import java.io.Serializable;

/**
 * @Description: 业务类异常
 * @author 张瑶
 * @date 2018/4/20 14:30
 * 
 */
public class ServiceException extends RuntimeException implements Serializable

   private static final long serialVersionUID = 1213855733833039552L;

   public ServiceException() 
   

   public ServiceException(String message) 
      super(message);
   

   public ServiceException(String message, Throwable cause) 
      super(message, cause);
   

 

技术图片

三:添加异常处理配置

打开上篇文章创建的WebConfigurer,添加如下方法

@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) 
    exceptionResolvers.add(getHandlerExceptionResolver());


/**
 * 创建异常处理
 * @return
 */
private HandlerExceptionResolver getHandlerExceptionResolver()
    HandlerExceptionResolver handlerExceptionResolver = new HandlerExceptionResolver()
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                             Object handler, Exception e) 
            RetResult<Object> result = getResuleByHeandleException(request, handler, e);
            responseResult(response, result);
            return new ModelAndView();
        
    ;
    return handlerExceptionResolver;


/**
 * 根据异常类型确定返回数据
 * @param request
 * @param handler
 * @param e
 * @return
 */
private RetResult<Object> getResuleByHeandleException(HttpServletRequest request, Object handler, Exception e)
    RetResult<Object> result = new RetResult<>();
    if (e instanceof ServiceException) 
        result.setCode(RetCode.FAIL).setMsg(e.getMessage()).setData(null);
        return result;
    
    if (e instanceof NoHandlerFoundException) 
        result.setCode(RetCode.NOT_FOUND).setMsg("接口 [" + request.getRequestURI() + "] 不存在");
        return result;
    
    result.setCode(RetCode.INTERNAL_SERVER_ERROR).setMsg("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员");
    String message;
    if (handler instanceof HandlerMethod) 
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s", request.getRequestURI(),
                handlerMethod.getBean().getClass().getName(), handlerMethod.getMethod() .getName(), e.getMessage());
     else 
        message = e.getMessage();
    
    LOGGER.error(message, e);
    return result;


/**
 * @Title: responseResult
 * @Description: 响应结果
 * @param response
 * @param result
 * @Reutrn void
 */
private void responseResult(HttpServletResponse response, RetResult<Object> result) 
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-type", "application/json;charset=UTF-8");
    response.setStatus(200);
    try 
        response.getWriter().write(JSON.toJSONString(result,SerializerFeature.WriteMapNullValue));
     catch (IOException ex) 
        LOGGER.error(ex.getMessage());
    

 

技术图片

四:添加配置文件

Spring Boot 中, 当用户访问了一个不存在的链接时, Spring 默认会将页面重定向到 **/error** 上, 而不会抛出异常. 

既然如此, 那我们就告诉 Spring Boot, 当出现 404 错误时, 抛出一个异常即可. 

在 application.properties 中添加两个配置: 

spring.mvc.throw-exception-if-no-handler-found=true 

spring.resources.add-mappings=false 
技术图片

上面的配置中, 第一个 spring.mvc.throw-exception-if-no-handler-found 告诉 SpringBoot 当出现 404 错误时, 直接抛出异常. 第二个 spring.resources.add-mappings 告诉 SpringBoot 不要为我们工程中的资源文件建立映射.

五:创建测试接口

package com.example.demo.service.impl;

import com.example.demo.core.ret.ServiceException;
import com.example.demo.dao.UserInfoMapper;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:56
 */
@Service
public class UserInfoServiceImpl implements UserInfoService

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo selectById(Integer id)
        UserInfo userInfo = userInfoMapper.selectById(id);
        if(userInfo == null)
            throw new ServiceException("暂无该用户");
        
        return userInfo;
    
技术图片

UserInfoController.java

package com.example.demo.controller;

import com.example.demo.core.ret.RetResponse;
import com.example.demo.core.ret.RetResult;
import com.example.demo.core.ret.ServiceException;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:39
 */
@RestController
@RequestMapping("userInfo")
public class UserInfoController 

    @Resource
    private UserInfoService userInfoService;

    @PostMapping("/hello")
    public String hello()
        return "hello SpringBoot";
    

    @PostMapping("/selectById")
    public RetResult<UserInfo> selectById(Integer id)
        UserInfo userInfo = userInfoService.selectById(id);
        return RetResponse.makeOKRsp(userInfo);
    

    @PostMapping("/testException")
    public RetResult<UserInfo> testException(Integer id)
        List a = null;
        a.size();
        UserInfo userInfo = userInfoService.selectById(id);
        return RetResponse.makeOKRsp(userInfo);
    


技术图片

六:接口测试

访问192.168.1.104:8080/userInfo/selectById参数 id:3


    "code": 400,
    "data": null,
    "msg": "暂无该用户"
技术图片

访问192.168.1.104:8080/userInfo/testException


    "code": 500,
    "data": null,
    "msg": "接口 [/userInfo/testException] 内部错误,请联系管理员"
技术图片

项目地址

码云地址: https://gitee.com/beany/mySpringBoot

GitHub地址: https://github.com/MyBeany/mySpringBoot

写文章不易,如对您有帮助,请帮忙点下star技术图片技术图片?

结尾

springboot添加全局异常处理已完成,后续功能接下来陆续更新。另求各路大神指点,感谢大家。

2018最新springboot2.0教程(零基础入门)

一、零基础快速入门SpringBoot2.01、SpringBoot2.x课程全套介绍和高手系列知识点简介:介绍SpringBoot2.x课程大纲章节java基础,jdk环境,maven基础2、SpringBoot2.x依赖环境和版本新特性说明简介:讲解新版本依赖环境和springboot2新特性概述3... 查看详情

springboot2.0:重磅springboot2.0权威发布

就在昨天SpringBoot2.0.0.RELEASE正式发布,今天早上在发布SpringBoot2.0的时候还出现一个小插曲,将SpringBoot2.0同步到Maven仓库的时候出现了错误,然后SpringBoot官方又赶紧把GitHub上发布的v2.0.0.RELEASE版本进行了撤回。到了下午将问题修复... 查看详情

springboot2.0系列教程springboot框架添加swagger2来在线自动生成接口的文档+测试功能(代码片段)

Hello大家好,本章我们添加Swagger2来在线自动生成接口的文档+测试功能。有问题可以联系我[email protected]。另求各路大神指点,感谢一:什么是SwaggerSwagger是一款通过我们添加的注解来对方法进行说明,来自动生成项目的在线a... 查看详情

springboot2.0干货系列:springboot1.5x升级到2.0指南

...,就把本博客中SpringBoot干货系列对应的源码从1.5X升级到SpringBoot2.0,顺便整理下升级的时候遇到的一些坑,做个记录。后续的教程就以最新的2.03版本为主。依赖JDK版本升级2.x至少需要JDK8的支持,2.x里面的许多方法应用了JDK8的许... 查看详情

springboot2.0.2教程-目录

SpringBoot2.0.2教程-HelloWorld-01 SpringBoot2.0.2教程-HelloWorld之intellijidea创建web项目-02 SpringBoot2.0.2教程-配置文件application.properties-03 SpringBoot2.0.2教程-日志管理-04  SpringBoot2.0.2教 查看详情

springboot2.0图文教程|集成邮件发送功能

...springboot/spring-boots-send-mail大家好,后续会间断地奉上一些SpringBoot2.x相关的博文,包括SpringBoot2.x教程和SpringBoot2.x新特性教程相关,如WebFlux等。还有自定义Starter组件的进阶教程,比如:如何封装一个自定义图 查看详情

零基础快速入门springboot2.0教程

一、SpringBoot2.x使用Dev-tool热部署简介:介绍什么是热部署,使用springboot结合dev-tool工具,快速加载启动应用官方地址:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#using-boot-devtools核心依赖包:<dependency 查看详情

使用docker构建部署运行springboot应用《springboot2.0极简教程》

使用Docker构建部署运行SpringBoot应用《SpringBoot2.0极简教程》image.pngimage.pngimage.pngimage.png。。。image.pngimage.pngimage.png。。。image.pngimage.pngimage.pngimage.png 查看详情

springboot2.0深度实践之核心技术篇

第1章系列总览总览SpringBoot2.0深度实践系列课程的整体议程,包括SpringBoot三大核心特性(组件自动装配、嵌入式Web容?、生产准备特性)、Web应用(传统Servlet、SpringWebMVC、SpringWebFlux)、数据相关(JDBC、JPA、事务)、功能扩展(Sp... 查看详情

springboot2.0整合同时支持jsp+html跳转(代码片段)

springboot项目创建教程 https://blog.csdn.net/q18771811872/article/details/88126835springboot2.0跳转html教程 https://blog.csdn.net/q18771811872/article/details/88312862springboot2.0跳转jsp教程 https:/ 查看详情

零基础快速入门springboot2.0教程

一、JMS介绍和使用场景及基础编程模型简介:讲解什么是小写队列,JMS的基础知识和使用场景1、什么是JMS:Java消息服务(JavaMessageService),Java平台中关于面向消息中间件的接口2、JMS是一种与厂商无关的API,用来访问消息收发系统... 查看详情

springboot2.0详述(代码片段)

SpringBoot2.0详述2018.2.22版权声明:本文为博主chszs的原创文章,未经博主允许不得转载。SpringBoot2.0即将发布,目前已经发布了v2.0.0RC2版,据传说下周可能就会正式发布。SpringBoot2.0有一系列重大的改变,下面将一... 查看详情

微服务springboot视频最新springboot2.0.3版本技术视频教程免费学习

超火爆的springboot微服务技术怎么学,看这里,springboot超详细的教程↓↓↓↓↓↓https://ke.qq.com/course/179440?tuin=9b38664001.springboot介绍02.微服务介绍03.springboot第一个例子04.Springboot中的常用注解分析05.springboot启动配置分析06.springboot... 查看详情

新课上线-java核心技术典型案例与面试实战系列二(springboot2.0+企业真实案例)

光阴似箭、岁月如梭转眼间已至2020年末想到这一年发生的糟心事不由得感慨万千、思绪横飞记忆犹新者莫过于肆意妄为的新冠病毒有多少华夏儿女因此离开人世有多少社会人儿因此失业破产有多少名胜古迹也因此失去往日繁华... 查看详情

springboot2.0.8跳转html页面

springboot项目创建链接 https://blog.csdn.net/q18771811872/article/details/88126835springboot2.0跳转jsp教程 https://blog.csdn.net/q18771811872/article/details/88342298jsp+html跳转整合 https://blog.csd 查看详情

springboot2.0:dockercompose+springboot+

我知道大家这段时间看了我写关于docker相关的几篇文章,不疼不痒的,仍然没有感受docker的便利,是的,我也是这样认为的,Iknowyourfelling。前期了解概念什么的确实比较无聊,请不要着急精彩马上开始,当大家对docker相关概念... 查看详情

springboot2:springboot2.0新特性

SpringBoot2(一):SpringBoot2.0新特性SpringBoot依赖于Spring,而SpringCloud又依赖于SpringBoot,因此SpringBoot2.0的发布正式整合了Spring5.0的很多特性,同样后面SpringCloud最新版本的发布也需要整合最新的SpringBoot2.0内容。一、新版本特性1,基于J... 查看详情

springcloudalibaba系列之gateway(网关)

...算整合zuul2.0了。SpringCloudGateway是Spring公司基于Spring5.0,SpringBoot2.0和Proj 查看详情