问题
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