Throw exception from controller


#1

Hello,

How can I throw an exception from a controller?
For example: I want to throw a 404 exception from my users controller.

How can I do that?


#2

Please share some code on what you have tried so far. Do not treat the forum as a way to spoonfeed you. There are 100 ways to return a 404 and I believe, no one can tell you all


#3

Hello,

I want to “summon” a 404 youch page, to be able to handle it as a normal 404 error.

I currently have:

'use strict'

const User = use('App/Models/User')

class UsersController {
  // ...

  show ({ response, params, view }, next) {
    const user = await User.query()
      .where('id', params.id)
      .setHidden(['password'])
      .with('group')
      .first()

    if (! user) {
      response.status(404)
      return view.render('errors.404')
    }

    return view.render('pages.users.show', { user: user.toJSON() })
  }

  // ...
}

module.exports = UsersController

And I want to change:

if (! user) {
  response.status(404)
  return view.render('errors.404')
}

To something like:

if (! user) {
  throw new Exception('404...', 404 /* ... */)
}

And then return a youch page.
How can I do that?

Thanks a lot. :slight_smile:


#4

Make use of AdonisJs generic exceptions as follows.

const { HttpException } = use('@adonisjs/generic-exceptions')
throw new HttpException('Not found', 404)

#5

Thanks a lot.

You’re the man. :smile: