node.js with express - showing custom error message

I am using node.js and express and I want to show custom error message when the requested page is not found. Currently I am doing it by using a Wildcards. If any of the routes doesn't match then the last route gets invoked. Is there any other better way to do this??

My routes

app.get('/', routes.index);
app.get('/users', user.list);
app.get('/hello', hello.hello);
app.get('/*', error.error);

Upvotes: 2

Views: 407

Answers (1)

Akshat Jiwan Sharma
Akshat Jiwan Sharma

Reputation: 16000

What you are doing is good. The only thing I would change is the order of routes like so

 app.get('/users', user.list);
 app.get('/hello', hello.hello);
 app.get('/', routes.index);
 app.get('/*', error.error);

A good rule to follow is define all least general routes first. As you probably know this basically tells express that if no other route is found show an error message and wild cards are a pretty good way to do it.

Upvotes: 3

Related Questions