开发者

When handling exceptions in OpenRasta handlers, what is the best way to convert to a response?

开发者 https://www.devze.com 2023-01-25 08:45 出处:网络
I\'m using OpenRasta 2.0 to build a REST API and its extensibility is fantastic - we\'ve managed for instance to plug-in OAuth authentication using DotNetOpenAuth fairly painlessly.

I'm using OpenRasta 2.0 to build a REST API and its extensibility is fantastic - we've managed for instance to plug-in OAuth authentication using DotNetOpenAuth fairly painlessly.

However I've come to the point now where I need to define our responses for error conditions. We're adopting the standards regarding HTTP error codes - but I'm concious of returning meaningful responses as well, pretty much like Twitter (the perennial example of REST) does:

{
 "error":"This method requires authentication.",
 "request":"\/1\/statuses\/followers.json"
}

Is the best way to return an OperationResult from all of our handlers, manually capture exceptions and map to a ResponseResource? This seems to me to be a fair amount of overhead compared with how the rest of OpenRasta functions.

Or should we write some kind of contributor to capture exceptions thrown in the pipeline and globally handle the issues? Perhaps translating only exceptions of particular types (RestException?).

Basically I'm after a feeling for what the best practice for this would be and how others have handled it.

Thanks.

EDIT:

After looking at this for some time today I'm having trouble figuring out how to wrap the handler call - I've declared myself a OperationInterceptor derived class and have hooked that into the pipeline with ResourceSpace.Uses.PipelineContributor<OperationInterceptorContributor>() and set a custom dependency up ResourceSpace.Uses.CustomDependency<IOperationInterceptor, ExceptionHandlerInterceptor>(DependencyLifetime.PerRequest) but no matter in which of the methods I try and wra开发者_开发问答p in a try-catch, the exception still bubbles.

Is it RewriteOperation, BeforeExecute or AfterExecute that is the most appropriate place to trap - and if so can you give me a clue as to how to start?

Thanks.


There's a couple of things you can do to achieve what you want.

First, you can build an IOperationInterceptor that wraps the call to your handler in a try/catch block, and assign the correct OperationResult on the ICommunicationContext.

Then if you want this to be serialized in json, you'll want to assign the ResponseResource property of your operationresult to a type that describes your error (let's call it "TitsUpResource" for now).

Finally, register that type as a resource with no URI, so you can add the json codec to it

ResourceSpace.Has.ResourcesOfType().WithoutUri.TranscodedBy or whatever else you may want.

0

精彩评论

暂无评论...
验证码 换一张
取 消