Java 异常的 Http 状态代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48139728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Http status code for Exceptions
提问by Carlos Mario
i have a SpringBoot controller, and i want to return the correct http code status for Exceptions. So, my question is: Which http statu code is better for Exception the "500" one or "409" one?
我有一个 SpringBoot 控制器,我想为异常返回正确的 http 代码状态。所以,我的问题是:哪个 http 状态代码更适合“500”或“409”例外?
This is my code:
这是我的代码:
@PostMapping(value = {"", "/"})
public ResponseEntity<Response> create(@RequestBody StudioDto studioDto,
ServletRequest servletRequest, ServletResponse servletResponse) {
Response response = new Response();
try {
studioService.createStudio(studioDto);
response.setMessage("The studio was create");
response.setStatusCode(HttpServletResponse.SC_CREATED);
} catch (Exception e) {
response.setMessage("Op we have a little problem");
response.setErrorMessage(e.getMessage());
//Which one
//this one 5xx
response.setStatusCode(500);
//Or this one 4xx
response.setStatusCode(409);
}
return new ResponseEntity(response, response.getHttpStatus());
}
采纳答案by Amer Qarabsa
This is not the recommended way to handle exceptions, you should use controller advice , check this link
这不是处理异常的推荐方法,您应该使用控制器建议,检查此链接
The status code is defined by the specific scenario , 500 means internal server error which I would use for a problem which it's cause is not specified, for 409 it resembels conflict on the target resource
状态代码由特定场景定义,500 表示内部服务器错误,我将用于解决未指定原因的问题,对于 409,它类似于目标资源上的冲突
The request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request
由于与目标资源的当前状态冲突,无法完成请求。此代码用于用户可能能够解决冲突并重新提交请求的情况
you have many other status code which is suitable in different cases so I would say no specific status code is the right answer, you can check this linkfor more info
您还有许多其他适用于不同情况的状态代码,所以我想说没有特定的状态代码是正确的答案,您可以查看此链接以获取更多信息
回答by Todd
It depends on what message you are trying to convey. Think of the status code as guidance to the caller on what to do next. If it's an internal server error that the user is unlikely to be able to do anything about, a 500error is appropriate.
这取决于您要传达的信息。将状态代码视为呼叫者下一步操作的指南。如果这是用户不太可能采取任何措施的内部服务器错误,则500错误是合适的。
The server encountered an unexpected condition that prevented it from fulfilling the request.
服务器遇到了阻止它完成请求的意外情况。
On the other hand, a 409indicates a conflict that the user could conceptually resolve:
另一方面,409表示用户可以在概念上解决的冲突:
The request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request.
由于与目标资源的当前状态冲突,无法完成请求。此代码用于用户可能能够解决冲突并重新提交请求的情况。
Most 400-level errors indicate that the user could, in theory, fix them and resubmit.
大多数 400 级错误表明用户理论上可以修复它们并重新提交。
Personally, I would advise you to catch more exact exceptions and determine which status code each should return, because it really depends on your use case. As of now, you are catching Exception
, and that could be just about anything so it's hard to tell what kind of guidance you should give the caller.
就个人而言,我建议您捕获更准确的异常并确定每个异常应返回哪个状态代码,因为这实际上取决于您的用例。到目前为止,您正在捕捉Exception
,这几乎可以是任何事情,因此很难说出您应该给来电者什么样的指导。
回答by davidxxx
5.XX codes mean error from the server side and 4.XXX codes mean error from the client side.
Here you catch any exception :
5.XX 码表示服务器端出错,4.XXX 码表示客户端出错。
在这里您可以捕获任何异常:
catch (Exception e) {
response.setMessage("Op we have a little problem");
response.setErrorMessage(e.getMessage());
//Which one
//this one 5xx
response.setStatusCode(500);
//Or this one 4xx
response.setStatusCode(409);
}
So it is clearly impossibleto know if the problem came from the client request (bad parameter for example) or from a server error (inconsistency in DB or programmatic error for example).
因此,显然不可能知道问题是来自客户端请求(例如错误的参数)还是来自服务器错误(例如数据库不一致或程序错误)。
To be able to set with precision 4.XXX or 5.XXX, your code could rely on some specific base exceptions as ClientErrorException
and ServerErrorException
.
为了能够以 4.XXX 或 5.XXX 的精度进行设置,您的代码可以依赖于一些特定的基本异常,如ClientErrorException
和 ServerErrorException
。
Throw one or the other according to the error cause and you could then rely on them to set the correct status code :
根据错误原因抛出一个或另一个,然后您可以依靠它们来设置正确的状态代码:
try {
studioService.createStudio(studioDto);
response.setMessage("The studio was create");
response.setStatusCode(HttpServletResponse.SC_CREATED);
}
catch (ClientErrorException e) {
response.setStatusCode(409);
}
catch (ServerErrorException e) {
response.setStatusCode(500);
}
Another way could be to add the status code field in the exception base class.
You could so simply write :
另一种方法是在异常基类中添加状态代码字段。
你可以这么简单地写:
try {
studioService.createStudio(studioDto);
response.setMessage("The studio was create");
response.setStatusCode(HttpServletResponse.SC_CREATED);
}
catch (MyRestException e) {
response.setStatusCode(e.getStatusCode());
}
These custom exceptions could be thrown directly from your code as you detect an error in the client request (4.XXX
).
In this way, you could consider all other exceptions as related to server processing (5.XXX
).
A Spring Exception Handler could easily perform this task.
当您在客户端请求 ( 4.XXX
) 中检测到错误时,可以直接从您的代码中抛出这些自定义异常。
通过这种方式,您可以将所有其他异常视为与服务器处理 ( 5.XXX
) 相关。
Spring Exception Handler 可以轻松执行此任务。
回答by paulsm4
Todd gave a great link. This is a better way of thinking about it:
托德给了一个很好的链接。这是一个更好的思考方式:
1×× Informational
2×× Success
3×× Redirection
4×× Client Error * 400 Bad Request * 401 Unauthorized ... * 405 Method Not Allowed ...
5×× Server Error * 500 Internal Server Error * 501 Not Implemented * 502 Bad Gateway ...
1×× 信息
2×× 成功
3×× 重定向
4×× 客户端错误 * 400 错误请求 * 401 未经授权 ... * 405 方法不允许 ...
5×× 服务器错误 * 500 内部服务器错误 * 501 未实现 * 502 网关错误...
In other words, each major number (200, 400, 500, etc.) is a CATEGORY. You can "refine" the error code by choosing a specific error within the "category".
换句话说,每个主要数字(200、400、500 等)都是一个CATEGORY。您可以通过选择“类别”中的特定错误来“优化”错误代码。
To your original question:
对于您的原始问题:
If the Client requestis "bad" (for example, illegal username/password), then return a 4xx.
If the Serversomehow fails (for example, you can't read the database), then return a 5xx.
如果客户端请求“错误”(例如,非法用户名/密码),则返回 4xx。
如果服务器以某种方式失败(例如,您无法读取数据库),则返回 5xx。
The "official" list of HTTP error codes is RFC 7231:
HTTP 错误代码的“官方”列表是 RFC 7231: