Exits custom Sails 1 and Actions 2

梦想的初衷 提交于 2019-12-12 00:59:39

问题


If I want to return an output with some error with status code and error message in sails 1 using Actions 2. How to do?

EX:

...

  exits: {
    notFound: {
      description: 'not found',
      responseType: 'notFound'
    }

...

How would it be to make an exit? For example: with status code 403 and message "Not allowed"


回答1:


EDIT: I tried the naive way and it worked! You can return with a non success exit as a function and pass a json as an argument. Example code:

return exits.notfound({
    error: true,
    message: 'The *thing* could not be found in the database.'
});

ORIGINAL ANSWER:

You can access the response object from an action 2 and put you error code and message there.

In your exit just set the statusCode you want and in the action itself modify your res accordingly to the specific exit before throwing it.

...

exits: {
    notFound: {
      statusCode: 403,
      description: 'not found'
    }

...

And in your action:

...

if(!userRecord) {
  this.res.message = 
    {
        exit: 'notFound', 
        message: 'The *thing* could not be found in the database.'
    };
  throw 'notFound';
}

...

You could setup a custom response to do the same thing. Put the responseType in your action 2 exit like this:

...

exits: {
    notFound: {
      responseType: 'notfound',
      description: 'not found'
    }

...

Then create your custom response in api/responses and set the status code and message there.

...

module.exports = function notfound() {
    let req = this.req;
    let res = this.res;

    sails.log.verbose('Ran custom response: res.notfound()');

    res.message = 
        {
            exit: 'notFound', 
            message: 'The *thing* could not be found in the database.'
        };
      return res.status(403);
    }

...


来源:https://stackoverflow.com/questions/51047831/exits-custom-sails-1-and-actions-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!