Spring Boot HTTP状态而不会引发异常 [英] Spring Boot HTTP status without throwing exceptions

查看:66
本文介绍了Spring Boot HTTP状态而不会引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回200以外的HTTP状态,而不使用 @ExceptionHandler 注释.

I want to return HTTP status other than 200 without using the @ExceptionHandler annotation.

之所以这样做,是因为并非每次对我的应用程序的调用都会导致异常,至少在我看来,这不会导致异常状态.

The reason for this is that not every call to my application, which results in a status which is not OK should throw an exception, at least not in my opinion.

作为一个例子,如果用户试图登录系统,但是提供了不正确的密码,我认为没有理由为了能够返回401状态而为此抛出异常.相反,我希望能够从常规"方法中返回状态.

As an example, if a user is trying to log into the system, but provides an inaccurate password, I see no reason to throw an exception over this just in order to be able to return a 401 status. Instead, I would like to be able to return the status from within a "regular" method.

其背后的原因是,抛出不必要的异常既会使我的日志文件混乱,又会使用"我的日志聚合器(Rollbar/Sentry)每月津贴.

The reason behind this is that throwing unnecessary exceptions both clutters my log files, and "uses" my log aggregator (Rollbar/Sentry) monthly allowance.

我尝试使用 @ResponseStatus @ResponseBody 注释方法,但是没有用.

I've tried annotating methods with @ResponseStatus and @ResponseBody, but it didn't work.

我到处寻找有关此问题的博客文章或其他文章,但找不到任何东西.

I looked around for blog posts or other articles on the issue but couldn't find anything.

知道这是否可行吗?

推荐答案

您可以使用 RessponseEntity .将/* STATUS CODE */替换为您想要的任何内容:

You can use RessponseEntity. Replace the /*STATUS CODE*/ with whatever you want:

@GetMapping("/url")
@ResponseBody
public ResponseEntity<?> handlerMethod(/*parameters*/) {
    // ...
    return ResponseEntity.status(/*STATUS CODE*/).body(...);
}

这篇关于Spring Boot HTTP状态而不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆