springboot 异常捕获

本文介绍了一个Spring Boot应用中统一处理特定异常(SystemException)的方法。通过@ControllerAdvice注解定义了一个全局异常处理器,该处理器能够捕获并处理所有控制器抛出的SystemException异常,并返回一个固定的HTTP状态码200和简单的响应消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.fuwo.headline.common.exception;

import org.springframework.http.HttpHeaders;
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.context.request.WebRequest;

import java.io.IOException;


@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(SystemException.class)
    public ResponseEntity<Object> handleDataNotFoundException(SystemException ex, WebRequest request) throws IOException {
        return new ResponseEntity<Object>(
                "ok", new HttpHeaders(), HttpStatus.OK);
    }

}




                
在Spring Boot中,可以通过统一异常处理机制来捕获和处理逻辑异常。这样的机制可以让我们在发生异常时返回给前端一个友好且易于理解的错误信息,而不是默认的服务器错误页面。 一种常见的实现方法是使用@ControllerAdvice注解,结合@ExceptionHandler注解来定义全局异常处理类。在该类中,我们可以编写方法来处理各种类型的异常,并返回自定义的错误信息。这样,在代码中发生异常时,会自动调用对应的处理方法来处理异常。 你可以参考引用中提供的示例代码来了解更详细的实现方法。在这个示例中,通过使用@ControllerAdvice注解和@ExceptionHandler注解,对不同类型的异常进行了捕获和处理,并返回了自定义的错误信息。 如果你对结果集的详细内容感兴趣,可以参考引用提供的文章链接,里面可能会有更多关于Spring Boot统一异常捕获的相关信息。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot逻辑异常统一处理方法](https://download.youkuaiyun.com/download/weixin_38705004/12745762)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springboot之全局异常捕获](https://blog.youkuaiyun.com/niulinbiao/article/details/120153502)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值