Teasim catches all the errors thrown in the handler, classifies the error code, and pipes them to onError middleware.
newTeasim().onError(({ code, error })=>{returnnewResponse(error.toString());}).get("/",()=>{thrownewError("Server is during maintainance");return"unreachable";});
With onError you can catch and transform the error into your custom error message.
TIP
It's important that onError must be called before the handler you want to apply it to.
For example, returning custom 404 messages:
import{ Teasim, NotFoundError }from"teasim";newTeasim().onError(({ code, error, set })=>{if(code ==="NOT_FOUND"){ set.status =404;return"Not Found :(";}}).post("/",()=>{thrownewNotFoundError();}).listen(8080);
Teasim supports custom error both in the type-level and implementation level.
Helping you to easily classify and narrow down the error type for full type safety with auto-complete:
classCustomErrorextendsError{constructor(public message:string){super(message);}}newTeasim().addError({ MyError: CustomError,}).onError(({ code, error })=>{switch(code){// With auto-completioncase"MyError":// With type narrowing// Error is typed as CustomErrorreturn error;}}).get("/",()=>{thrownewCustomError("Hello Error");});
To list all errors, you can list an error using error.all.
newTeasim().post("/",({ body })=> body,{ body: t.Object({ name: t.String(), age: t.Number(),}),error({ code, error }){switch(code){case"VALIDATION":console.log(error.all);// Find a specific error name (path is OpenAPI Schema compliance)const name = error.all.find(x => x.path ==="/name");// If has validation error, then log itif(name)console.log(name);}},});
With this you can overwrite provide an advance custom error message or monitor an error based on your need.
TIP
Make sure to narrow down Error code to "Validation" to narrow down error type before using error.all