找不到资源时抛出异常是否正确 [英] is it correct to throw an exception when resource not found

查看:63
本文介绍了找不到资源时抛出异常是否正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找不到请求的资源时在服务器端抛出异常可以吗?

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:

  • You can throw a WebApplicationException, that will be mapped a response. You can define your own subclasses of WebApplicationException or use the existing ones. The NotFoundException, for example, will be mapped to a response with the 404 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.

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