Thursday, September 21, 2017

Handling http Error With Boom

Here is an interesting blog about handling http error using boom with custom message. As per the requirment we can put custom message here so that error comes with proper error message.

Boom provides set of utilities for returning HTTP errors. we can make it custom for sending proper error message along with http error.

Pre required plugins
  • npm install boom
var Boom=require('boom')
Using boom plugings a user can be authenticated along with custom error message.
Boom.unauthorized([message],[schema],[attributes])

here 'message' is optional,
'schema' can be an authentication schema name or array of string values.
'attributes'- attributes is an object of values to user in case setting the 'www-authenticate' header.


Here is code:

Example: #1
1
2
<span style="color:#000000;"> Boom.unauthorized('invalid password');
 </span>
1
2
3
4
5
6
7
8
<span style="color:#000000;"> generate the response like this
 
"payload":{
"statusCode":"401",
"error""unauthorized"
"message":"invalid user or password"
}
 </span>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<span style="color:#000000;">In case of invalid query
 
Boom.badRequest([message],[data]); //message and data are optional
i.e
Boom.badRequest("invalid data")
The response will be like this
"payload":{
"statusCode":"400",
"error""Bad Request"
"message":"invalid data;
}
  
 
Here is list of functions which can be used to handle the http errors.
Boom.notFound("Your custom message here")
Boom.methodNotAllowed([message],[data],[allow])
 </span>
1
2
<span style="color:#000000;">
 </span>
message-Its optional.
data-additional error data(optional).
allow-optional(string or array of string)
1
2
3
4
5
6
7
8
9
<span style="color:#000000;">Boom.methodNotAllowed("This metthod is not allowed")
 
Error response:
"payload":{
"statusCode":"405",
"error":"Method Not Allowed",
"message":"This method is not allowed"
}
 </span>
1
2
3
4
5
6
7
8
9
<span style="color:#000000;">//Request-time-out
Boom.requestTimeOut("time out")
Response:
"payload":{
"statusCode":"408",
"error":"Request time-out",
"message":"time out"
}
 </span>

1
2
3
4
5
6
7
8
9
<span style="color:#000000;">//un-supported media
Boom.unsupportedMediaType("This media is not supported")
Error response:
"payload":{
statusCode":"415",
"error":"Unsupported media type",
"This media is not supported"
}
 </span>

No comments:

Post a Comment