简体   繁体   中英

Adonisjs: how to catch exception in lucid model creation?

I'm building RESTful api with adonisjs. I face this problem in jwt login module. Look at the code below:

async login({request, auth, response}) {

    let {email, password} = request.all()

    try {
      if (await auth.attempt(email, password)) {
        let user = await User.findBy('email', email)
        let token = await auth.generate(user)
        user.password = undefined
        Object.assign(user, token)
        //------------------------------------------
        const assignedToken = await Token.create({
          user_id: user.id,
          token,
        })
        // -------- i'd like to catch exception here...
        return response.json({
          success: true,
          user
        })
      }
    } catch(e) {
        return response.json({
          success: false,
          message: 'login_failed'
        })
    }
  }

I'd like to catch possible exception while persisting jwt token to database. I am rather new to adonis. I checked their doc but cannot find exact return type. Do they throw an exception? Or just return null/false? I have no idea. Do you have any?

Do they throw an exception?

Yes

An exception will appear if there is a problem during creation. You can create a new try/catch inside you try/catch. Like:

async login({request, auth, response}) {
...
  try {
    ...
    try { // New try/catch
      const assignedToken = await Token.create({
        user_id: user.id,
        token,
      })
    } catch (error) {
      // Your exception
      return ...
    }
    return response.json({
      success: true,
      user
    })
  }catch (e) {
    ...
  }
}

It's the simplest solution. I would do it this way because there can be different types of errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM