forked from DefinitelyTyped/DefinitelyTyped
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttperr-tests.ts
90 lines (80 loc) · 2.21 KB
/
httperr-tests.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/// <reference path="httperr.d.ts" />
import httperr = require('httperr');
// ----------------------------------------
// Basic usage example from: https://github.com/pluma/httperr/blob/1.0.0/README.md
var err = httperr[404]('The path "/example" could not be resolved');
console.log(err);
/*
{ [NotFound: The path "/example" could not be resolved]
title: 'Not Found',
name: 'NotFound',
code: 'NOT_FOUND',
statusCode: 404,
message: 'The path "/example" could not be resolved'
}
*/
throw err;
/*
NotFound: The path "/example" could not be resolved
at ...
*/
console.log(httperr.methodNotAllowed({allowed: ['GET', 'POST']}));
/*
{ [MethodNotAllowed]
title: 'Method Not Allowed',
name: 'MethodNotAllowed',
code: 'METHOD_NOT_ALLOWED',
statusCode: 405,
message: '',
allowed: ['GET', 'POST']
}
*/
err = new httperr.NotFound();
console.log(err);
/*
{ [NotFound]
title: 'Not Found',
name: 'NotFound',
code: 'NOT_FOUND',
statusCode: 404,
message: 'The path "/example" could not be resolved'
}
*/
console.log(err instanceof httperr.NotFound); // true
console.log(err instanceof httperr.notFound); // true
console.log(err instanceof httperr['404']); // true
console.log(err instanceof httperr.MethodNotAllowed); // false
console.log(err instanceof httperr.HttpError); // true
console.log(err instanceof Error); // true
// ----------------------------------------
// Advanced usage: creating custom Error subclasses
var Custom404Error = httperr.createHttpError(404, 'Not Found', config => {
this.message = 'The resource was not found';
this['some custom property'] = config.parameters['some custom parameter'];
});
err = new Custom404Error();
var Custom500Error = httperr.createHttpError(500, 'Something went wrong');
err = new Custom500Error();
// ----------------------------------------
// Advanced usage: returning a JSON serializable representation of an error
var err = httperr.notFound('File Not Found');
console.log(err.toObject());
/*
{
name: 'NotFound',
code: 'NOT_FOUND',
title: 'Not Found',
statusCode: 404,
message: 'File Not Found',
stack: '…'
}
*/
console.log(err.toObject('stack', /^title$/));
/*
{
name: 'NotFound',
code: 'NOT_FOUND',
statusCode: 404,
message: 'File Not Found'
}
*/