Is there any point in putting try/catch statements in each method of a controller?

I'm using Adonis JS as the API for my application. For each method in my controllers, I add try/catch statements to handle errors and return a response to my front-end in case one occurs.

  async createDiscussion({ request, auth, response }: HttpContext) {
    try {
     // my code here
    } catch (error) {
      return response.status(500).json({ error: true, message: '...'})
    }
   }
 

Is this necessary, or is it better to just use Adonis's exception handler?
Copied!

Join The Discussion! (1 Replies)

Please sign in or sign up for free to join in on the dicussion.

  1. Commented 1 day ago

    Unless there are certain endpoints you'd like to do something specific with, in terms of error handling, I would just rely on AdonisJS' exception handling. If you don't have try/catches in your controllers the exception handler will catch any exceptions that are thrown automatically for you.

    You can then update the handler to your liking if you're looking to always return a specific structure for exceptions.

    1

    Please sign in or sign up for free to reply