actix / actix-web

Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.
https://actix.rs
Apache License 2.0
21.6k stars 1.67k forks source link

[question] Recommended way to translate errors into different responses? #1018

Closed vmalloc closed 5 years ago

vmalloc commented 5 years ago

Assuming I have a handler function that internally calls several functions returning Result<T, Error> (Error being failure::Error), I'd like a convenient way of using ? on all those calls and have different specific errors map into different responses (some to Conflict for example, others to BadRequest and all the rest to internal server error as is the default).

I couldn't find a convenient way to achieve this with actix, although it feels like it should be possible. Is it?

Thanks in advance!

fafhrd91 commented 5 years ago

You can use enum for error and implement ErrorResponse trait for it

vmalloc commented 5 years ago

Indeed, but that just moves the translation into yet another place. For example, if I want to translate constraint violations errors from diesel into 409 errors, that would mean adding a match statement to translate it, and also a fallback to "all other errors", which failure::Error already provides...

Perhaps there's a way to do this with middleware?

fafhrd91 commented 5 years ago

how could you distinguish what error happen with failure::Error? if you need different responses you have to use different errors or enum as error

fafhrd91 commented 5 years ago

i use enums for errors with custom ErrorResponse impl. you are free to choose different approach

vmalloc commented 5 years ago

Given an Error and specific cases one wants to test against, there's downcast and downcast_ref for that purpose - check if an error is of a specific type...

vmalloc commented 5 years ago

So just to understand -- your enum would include something like ConflictError, BadRequestError and GeneralError(Error), each one translating to the correct response in the ErrorResponse implementation?

fafhrd91 commented 5 years ago

that is correct

vmalloc commented 5 years ago

I see. Thanks!

On Wed, 31 Jul 2019 at 18:12 Nikolay Kim notifications@github.com wrote:

that is correct

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/actix/actix-web/issues/1018?email_source=notifications&email_token=AAAHAJRUCNXE5YKK6WOFPC3QCGTWRA5CNFSM4IIHTLFKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD3HSQVI#issuecomment-516892757, or mute the thread https://github.com/notifications/unsubscribe-auth/AAAHAJWOCKP22YZNSTYTAG3QCGTWRANCNFSM4IIHTLFA .

-- Rotem