11

How do you return an error inside an operation hook?

Use case is sending a push notification after saving a new model instance.

I observe the 'after save' event, send the push. If this fails for whatever reason, I want to send a 500 response code. How do I do that?

I am unable to find documentation as to what the ctx object actually is or contains.

Customer.observe('after save', function(ctx, next) {

  //model saved, but sending push failed for whatever reason, and I want to now send a 500 error back to the user
  //how?  what's inside ctx? how do you send back a response?  
  next();
});
Laurel
  • 5,965
  • 14
  • 31
  • 57
user798719
  • 9,619
  • 25
  • 84
  • 123
  • 1
    You can inspect the ctx object with a `console.log(ctx)`. It is the context object that represents the request and associated data (`ctx.instance` is your Customer instance, for example). To pass errors through operation hooks, pass the error via `next(error);` as the last line in your hook. But that's where my understanding ends—I'm not sure where this ends up or how to handle it in a central place. – notbrain May 29 '15 at 22:56
  • You can use assert module to throw errors in clean way. – Virendra Singh Rathore Nov 08 '16 at 15:57

3 Answers3

12

I believe it's something along these lines:

var error = new Error();
error.status = 500;
next(error);
JBCP
  • 13,109
  • 9
  • 73
  • 111
Are Almaas
  • 1,063
  • 12
  • 26
  • `next(err)` returns the right object but pollute my logs with "unhandled error". I think that without `throw error` it shouldn't print that. What should I do? thanks – ClementWalter Apr 12 '18 at 19:04
9

Extending the previous answer, as I cannot add comments yet.

You can provide more information to the error response with:

var error = new Error();
error.status = 401;
error.message = 'Authorization Required';
error.code = 'AUTHORIZATION_REQUIRED';

This will return something like:

{
   "error": {
      "name": "Error",
      "status": 401,
      "message": "Authorization Required",
      "code": "AUTHORIZATION_REQUIRED",
      "stack": "Error: Authorization Required\n    at ..."
   }
}
JBCP
  • 13,109
  • 9
  • 73
  • 111
Shyri
  • 400
  • 1
  • 6
  • 15
0

There is detailed documentation on what ctx actually contains. It can be found in Loopback after-save operation hook docs.

The ctx object has the instance method which returns the model instance that was saved. You can return the error after checking the model instance like so:

if (ctx.instance) {
  // check if your push operation modified the instance
  // If condition is not met, throw the error
  var error = new Error()
  error.status = 500
  error.message = '...'
  next(error)
}

The documentation above covers the properties of the ctx object for the after save hook.

joshuaai
  • 41
  • 3