0

0

Spring Boot 中的异常处理

WBOY

WBOY

发布时间:2024-07-25 09:43:01

|

918人浏览过

|

来源于dev.to

转载

spring boot 中的异常处理

异常处理是构建健壮且用户友好的应用程序的关键部分。在 spring boot 中,我们可以通过多种方式处理异常,以确保我们的应用程序保持稳定并向用户提供有意义的反馈。本指南将涵盖异常处理的不同策略,包括自定义异常、全局异常处理、验证错误和生产最佳实践。

1. 异常处理基础知识

异常是扰乱程序正常流程的事件。它们可以分为:

  • checked exceptions: 在编译时检查的异常。
  • unchecked exceptions(运行时异常): 运行时发生的异常。
  • 错误: 应用程序不应处理的严重问题,例如 outofmemoryerror。

2. 自定义异常类

创建自定义异常类有助于处理应用程序中的特定错误情况。

package com.example.springbootrefresher.exception;

public class departmentnotfoundexception extends runtimeexception {
    public departmentnotfoundexception(string message) {
        super(message);
    }
}

3. 控制器中的异常处理

@exceptionhandler 注释:
您可以在控制器类中定义处理异常的方法。

package com.example.springbootrefresher.controller;

import com.example.springbootrefresher.exception.departmentnotfoundexception;
import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;

@restcontroller
public class departmentcontroller {

    @getmapping("/department")
    public string getdepartment() {
        // simulate an exception
        throw new departmentnotfoundexception("department not found!");
    }

    @exceptionhandler(departmentnotfoundexception.class)
    public responseentity<string> handledepartmentnotfoundexception(departmentnotfoundexception ex) {
        return new responseentity<>(ex.getmessage(), httpstatus.not_found);
    }
}

4. 使用@controlleradvice进行全局异常处理

要全局处理异常,可以使用@controlleradvice和集中式异常处理程序。

杰易OA办公自动化系统6.0
杰易OA办公自动化系统6.0

基于Intranet/Internet 的Web下的办公自动化系统,采用了当今最先进的PHP技术,是综合大量用户的需求,经过充分的用户论证的基础上开发出来的,独特的即时信息、短信、电子邮件系统、完善的工作流、数据库安全备份等功能使得信息在企业内部传递效率极大提高,信息传递过程中耗费降到最低。办公人员得以从繁杂的日常办公事务处理中解放出来,参与更多的富于思考性和创造性的工作。系统力求突出体系结构简明

下载
package com.example.springbootrefresher.error;

import com.example.springbootrefresher.entity.errormessage;
import com.example.springbootrefresher.exception.departmentnotfoundexception;
import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.responsestatus;
import org.springframework.web.context.request.webrequest;
import org.springframework.web.servlet.mvc.method.annotation.responseentityexceptionhandler;

@controlleradvice
@responsestatus
public class customresponseentityexceptionhandler extends responseentityexceptionhandler {

    @exceptionhandler(departmentnotfoundexception.class)
    public responseentity<errormessage> handledepartmentnotfoundexception(departmentnotfoundexception exception, webrequest request) {
        errormessage message = new errormessage(
                httpstatus.not_found.value(),
                exception.getmessage(),
                request.getdescription(false)
        );

        return responseentity.status(httpstatus.not_found)
                .body(message);
    }

    @exceptionhandler(exception.class)
    public responseentity<errormessage> handleglobalexception(exception exception, webrequest request) {
        errormessage message = new errormessage(
                httpstatus.internal_server_error.value(),
                exception.getmessage(),
                request.getdescription(false)
        );

        return responseentity.status(httpstatus.internal_server_error)
                .body(message);
    }
}

5. 创建标准错误响应

定义标准错误响应类来构建错误消息。

package com.example.springbootrefresher.entity;

public class errormessage {
    private int statuscode;
    private string message;
    private string description;

    public errormessage(int statuscode, string message, string description) {
        this.statuscode = statuscode;
        this.message = message;
        this.description = description;
    }

    // getters and setters

    public int getstatuscode() {
        return statuscode;
    }

    public void setstatuscode(int statuscode) {
        this.statuscode = statuscode;
    }

    public string getmessage() {
        return message;
    }

    public void setmessage(string message) {
        this.message = message;
    }

    public string getdescription() {
        return description;
    }

    public void setdescription(string description) {
        this.description = description;
    }
}

6. 处理验证错误

spring boot 与 bean validation (jsr-380) 集成良好。要全局处理验证错误,请使用@controlleradvice。

package com.example.springbootrefresher.error;

import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.validation.fielderror;
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.responsestatus;
import org.springframework.web.context.request.webrequest;
import java.util.hashmap;
import java.util.map;

@controlleradvice
@responsestatus
public class validationexceptionhandler extends responseentityexceptionhandler {

    @exceptionhandler(methodargumentnotvalidexception.class)
    public responseentity<map<string, string>> handlevalidationexceptions(methodargumentnotvalidexception ex) {
        map<string, string> errors = new hashmap<>();
        ex.getbindingresult().getallerrors().foreach((error) -> {
            string fieldname = ((fielderror) error).getfield();
            string errormessage = error.getdefaultmessage();
            errors.put(fieldname, errormessage);
        });
        return new responseentity<>(errors, httpstatus.bad_request);
    }
}

7. 使用@responsestatus处理简单异常

对于简单的情况,可以用@responsestatus注解异常类来指定http状态码。

package com.example.SpringBootRefresher.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class DepartmentNotFoundException extends RuntimeException {
    public DepartmentNotFoundException(String message) {
        super(message);
    }
}

8. 生产最佳实践

  1. 一致的错误响应:确保您的应用程序返回一致且结构化的错误响应。使用标准错误响应类。
  2. 日志记录: 记录异常以用于调试和监控目的。确保敏感信息不会在日志中暴露。
  3. 用户友好的消息:提供用户友好的错误消息。避免向用户暴露内部细节或堆栈跟踪。
  4. 安全: 请谨慎对待错误响应中包含的信息,以免暴露敏感数据
  5. 文档: 为您的团队和未来的维护人员记录您的异常处理策略。

概括

spring boot 中的异常处理涉及使用 @exceptionhandler、@controlleradvice 和 @responsestatus 等注释来有效地管理错误。通过创建自定义异常、处理验证错误并遵循最佳实践,您可以构建强大的应用程序,以优雅地处理错误并向用户提供有意义的反馈。使用 java 17 功能可确保您的应用程序利用 java 生态系统中的最新改进。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

156

2025.08.06

Java Spring Security 与认证授权
Java Spring Security 与认证授权

本专题系统讲解 Java Spring Security 框架在认证与授权中的应用,涵盖用户身份验证、权限控制、JWT与OAuth2实现、跨站请求伪造(CSRF)防护、会话管理与安全漏洞防范。通过实际项目案例,帮助学习者掌握如何 使用 Spring Security 实现高安全性认证与授权机制,提升 Web 应用的安全性与用户数据保护。

88

2026.01.26

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

139

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

408

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

73

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

148

2025.12.22

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

271

2025.12.24

Spring Boot企业级开发与MyBatis Plus实战
Spring Boot企业级开发与MyBatis Plus实战

本专题面向 Java 后端开发者,系统讲解如何基于 Spring Boot 与 MyBatis Plus 构建高效、规范的企业级应用。内容涵盖项目架构设计、数据访问层封装、通用 CRUD 实现、分页与条件查询、代码生成器以及常见性能优化方案。通过完整实战案例,帮助开发者提升后端开发效率,减少重复代码,快速交付稳定可维护的业务系统。

32

2026.02.11

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

3

2026.03.11

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PostgreSQL 教程
PostgreSQL 教程

共48课时 | 10.5万人学习

Django 教程
Django 教程

共28课时 | 4.9万人学习

Excel 教程
Excel 教程

共162课时 | 21万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号