找不到资源时抛出异常是否正确 [英] is it correct to throw an exception when resource not found
问题描述
找不到请求的资源时在服务器端抛出异常可以吗?
Is it fine to throw an exception on the server side when the requested resource was not found?
客户端收到未找到的404.我担心的是,在这种情况下在服务器端抛出异常是否正常/错误.
the client receives a 404 not found. My concern is whether it is fine/wrong to throw an exception on the server side when this happens.
推荐答案
很难假设您要添加到问题的详细信息级别上要做什么.
It's hard to assume what your are trying to do with the level of details you added to your question.
但是,如果您正确地处理了异常,则该方法可能没有任何问题.看看一些框架使用的方法:
However, if you handle the exceptions properly, there may be nothing wrong with that approach. Have a look at the approaches used by some frameworks:
-
您可以抛出
WebApplicationException
,将其映射为响应.您可以定义WebApplicationException
或使用现有的.NotFoundException
,例如,将映射到状态代码为404
的响应.有关现有例外的更多详细信息,请参阅此 answer .
You can throw a
WebApplicationException
, that will be mapped a response. You can define your own subclasses ofWebApplicationException
or use the existing ones. TheNotFoundException
, for example, will be mapped to a response with the404
status code. For more details on the existing exceptions, refer to this answer.
You also can create your own ExceptionMapper
to map any exception to a desired response.
-
您可以通过使用它还使您可以实现
AbstractHandlerExceptionResolver
.It also gives you the possibility to implement a
HandlerExceptionResolver
or extend one of the existing implementations, such as theAbstractHandlerExceptionResolver
.另一种方法是使用
@ControllerAdvice
并通过使用 <代码> @ExceptionHandlerAnother approach would be using a
ResponseEntityExceptionHandler
annotated with@ControllerAdvice
and define the handled exceptions by annotating the implemented method with@ExceptionHandler
这篇关于找不到资源时抛出异常是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!