Exception Handling
How does it work?
Exceptions in a Request environment are actually being thrown by the Backend, catched by the Frontend and then transformed to be used similarly like you would in the Backend.
For this to work, your Backend needs to adhere to a specific Request structure:
export type Response<T> = {
data: T
validations?: ResponseValidation
exception?: {
name: string
context?: ExceptionContext
}
meta?: ResponseMeta
links?: ResponseLinks
}As long as your Backend at least returns the name of the thrown Exception within this Type constraint, Spire can handle it.
To mimic our Backend behaviour in our Frontend, similarly to Requests and Resources, we clone all the Exceptions we want to handle in our Frontend:
export class AuthenticationException extends Error {
public constructor() {
super()
this.name = "AuthenticationException"
}
}INFO
We need the name specifically repeated in a string, otherwise it will be mangled by minification.
This way we can use this error in any try/catch block as follows:
try {
// do something
} catch(e: any) {
if(e.is(AuthenticationException)) {
// ohoh - user is not logged in, do something!
}
}INFO
Any Error thrown by Javascript needs to be either unknown or any since Errors/Exceptions can be thrown at any point in the callstack.
The whole Chain
Combined with Middleware this creates a top-down chain of exception handling.
Exception Middleware can catch exceptions and handle them globally, but they will still get propagated to component code, so you can also handle them there or only handle specific exceptions.
You might want to have more detailed error messages or error toasts in a component on an exception, than the middleware that will handle other things.