改装:如何有目的地为特定状态代码投掷apiexception
我正在尝试为我的 API 创建 Refit 库。
每当收到的状态代码不是 200 和 207 时,我想抛出 ApiExeption。
public interface IServiceAPIs{
[Post("/api/users/register")]
Task<HttpResponseMessage> PostData([Header]string auth,RegisterUserRequest registerUserRequest);
}
在我的实现类中:
try {
var response = service.PostData(auth,registerUsers);
if(!response.IsSuccessStatusCode){
throw new ApiException(); // Here I'm not able to find how to throw this exception
}
} catch(ApiException Ex) {
log.write(ex);
}
如何抛出异常。?
提前致谢。
I'm trying to create Refit library for my APIs.
I wanted to throw ApiExeption whenever status code received is other than 200 and 207.
public interface IServiceAPIs{
[Post("/api/users/register")]
Task<HttpResponseMessage> PostData([Header]string auth,RegisterUserRequest registerUserRequest);
}
and in my implementation class:
try {
var response = service.PostData(auth,registerUsers);
if(!response.IsSuccessStatusCode){
throw new ApiException(); // Here I'm not able to find how to throw this exception
}
} catch(ApiException Ex) {
log.write(ex);
}
How can I throw exception.?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我刚刚遇到了类似的要求,解决方案很简单。如果您在客户端使用REFIT,则每个BadRequest都会被捕获/处理为Apiexception。
您所要做的就是返回
返回badrequest(“异常消息”)
如果在不受控制的情况下要在服务或存储库中投掷异常。通过进行新异常(“”)
(异常应为gentregateException,nullexception等。不是直接的系统。exception),然后在下面的控件中捕获此异常,然后返回badrequest,这将返回作为客户端的apiexception。您的控制器端点主体。
I just came across the similar requirement and solution is quite simple. If you use refit on client side every BadRequest is caught/handled as ApiException by Refit.
All you have to do is return
return BadRequest("exception message")
if you want to throw an exception within somewhere your Service or Repository when not in control. Do that byThrow new Exception("")
(Exception should be AggregateException, NullException etc. not directly System.Exception), then catch this exception in your control like below and return BadRequest, this will be returned as ApiException on the client side.your controller endpoint body.