Created
January 2, 2023 19:04
-
-
Save samuelastech/601a65d7d2cad50c59fd7c779db4cf0a to your computer and use it in GitHub Desktop.
Handling errors in REST APIs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class ErrorCustom { | |
constructor(public message: string, public code: number){ | |
this.message = message | |
this.code = code | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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