Differentiate between errors #2698
Replies: 1 comment
-
Hi @miguel-arrf! I'm Dosu and I’m helping the openapi-ts team. You're right—openapi-ts currently generates error types as unions (like A more typesafe workaround is to write custom type guards that check for properties unique to each error type. For example, if function isErrorTypeFor409(error: unknown): error is ErrorTypeFor409 {
return typeof error === "object" && error !== null && "conflictReason" in error;
} Then use it like: if (status === 409 && error && isErrorTypeFor409(error)) {
return error;
} If your error types don't have unique properties, you can create a mapping function using the status code: function getTypedError(status: number, error: unknown): ErrorTypeFor409 | ErrorTypeFor404 | ErrorResponse | undefined {
switch (status) {
case 409:
return error as ErrorTypeFor409;
case 404:
return error as ErrorTypeFor404;
case 500:
return error as ErrorResponse;
default:
return undefined;
}
} But this is still not fully typesafe—it's just a centralized place for assertions. The feature request for discriminated unions keyed by status code is tracked in issue #495, but it's not implemented yet. For now, custom type guards are the most typesafe approach, and keeping assertions in one place helps if the error types change later. Keep an eye on the project for updates—if discriminated unions get added, this will become much easier! To reply, just mention @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi!
So, I have the following code (I'm simplifying it a lot, by omitting some values):
I'm rather new to Typescript, and there's some things that I still don't know how to do (and what they are). From my understanding from issues like this (#495) the problem is the lack of a
discriminated union
.The question is the following: is there a typesafe & elegant way of knowing, ok, if the status is 409, then the error is ErrorTypeFor409...?
Not to forget that on the generated code, we have this:
I really dislike having to do
as ErrorTypeFor409
andas ErrorTypeFor404
. What if in the future the status code 404 returns something different?Thank you!
Beta Was this translation helpful? Give feedback.
All reactions