Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate an 400 Bad Request (or any status code) with custom detail from a Service #166

Open
blogcraft opened this issue Mar 17, 2022 · 2 comments

Comments

@blogcraft
Copy link

If inside of a controller I return a StatusCode(400, "You missed something")

I will get a ProblemDetails object with a detail property with value "You missed something".

But most of my business logic is inside services. Is there any way to throw some kind of custom exception that generates a ProblemDetail object with the detail value in production? So I can show to the client user a readable reason of the failure?

Thanks

@khellang
Copy link
Owner

khellang commented Mar 17, 2022

Hey @blogcraft! 👋🏻

Is there any way to throw some kind of custom exception that generates a ProblemDetail object with the detail value in production?

Sure, you could just define your own exception type (or use some existing type) and configure its mapping to a ProblemDetails instance:

services.AddProblemDetails(x =>
{
    x.Map<MyCustomException>((ctx, ex) => /* return your problem details instance here */); 
});

@blogcraft
Copy link
Author

Thanks! That works perfect! :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants