Skip to content

Instantly share code, notes, and snippets.

@samuelastech
Created January 2, 2023 19:04
Show Gist options
  • Save samuelastech/601a65d7d2cad50c59fd7c779db4cf0a to your computer and use it in GitHub Desktop.
Save samuelastech/601a65d7d2cad50c59fd7c779db4cf0a to your computer and use it in GitHub Desktop.
Handling errors in REST APIs
export default class ErrorCustom {
constructor(public message: string, public code: number){
this.message = message
this.code = code
}
}
import ErrorCustom from './ErrorCustom.ts'
router.post('example', async (request, reply) => {
try{
const users = await Users.findMany()
if(!users) throw new ErrorCustom("Couldn't find any users", 404)
} catch (error) {
if(error instanceof ErrorCustom){
return reply.status(error.code).send({
status: false,
message: error.message
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment