How to raise custom error message in Sails.js

前提是你 提交于 2019-12-12 14:18:40

问题


I am very new to Sails.js (0.9.13) and to node style programming in general. Any help appreciated. The collowing example is from a UserController:

module.exports = {

    save: function (req, res) {

        var u = {    
            firstName: req.param('firstName'),
            lastName: req.param('lastName'),
            email: req.param('email'),
            password: req.param('password'),
        };

        User.create(u).done(function(err,user){
            if(err) {       
                if( err.code == 'ER_DUP_ENTRY' ) {
                    return new Error('Duplicate: email address already in use.','UserController');
                }
                console.log( err );
                return;
            } 
            console.log( user );
        });
   }
}

So I am trying to capture the 'ER_DUP_ENTRY' error code and return a custom error message, but I am having no luck as written. How exactly should I be doing this?


回答1:


If what you're intending is to return an error to the client, there are several ways to go, but all of them start with the res object that is passed as an argument to your controller action. All of the latest builds of Sails have a few basic error responses baked into that object, so you can do (for example):

res.serverError(err)

instead of return new Error to show a general error page with a 500 status code. For JSON-only API calls that don't expect HTML, it'll send a simple object with the status code and the error. There's also:

res.notFound() // 404 response
res.forbidden() // 403 response
res.badRequest() // 400 response

For your "duplicate entry" error, you'll probably want something more customized. Since your example is coming from a form post, the best practice would be to actually save the error as a flash message and redirect back to the form page, for example:

req.flash('error', 'Duplicate email address');
return res.redirect('/theView');

and then in your form view, display errors using something like:

<% if (req.session.flash && req.session.flash.error) { %><%=req.flash('error')%><% } %>

As an alternative, you could just display a custom error view from your controller:

return res.view('duplicateEmail');

If you're responding to an API call, you'll want to send a status code and (probably) a JSON object:

return res.json(409, {error: 'Email address in use'});

The point is, rather than returning (or throwing) an Error object in your controller code, you want to use the res object to respond to the request in some way.



来源:https://stackoverflow.com/questions/22572315/how-to-raise-custom-error-message-in-sails-js

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