UNPKG

4.2 kBPlain TextView Raw
1import path from 'path'
2import { NotFound, GeneralError } from '@feathersjs/errors'
3import { Request, Response, NextFunction, ErrorRequestHandler, RequestHandler } from 'express'
4
5const defaults = {
6 public: path.resolve(__dirname, '..', 'public'),
7 logger: console
8}
9const defaultHtmlError = path.resolve(defaults.public, 'default.html')
10
11export function notFound({ verbose = false } = {}): RequestHandler {
12 return function (req: Request, _res: Response, next: NextFunction) {
13 const url = `${req.url}`
14 const message = `Page not found${verbose ? ': ' + url : ''}`
15
16 next(new NotFound(message, { url }))
17 }
18}
19
20export type ErrorHandlerOptions = {
21 public?: string
22 logger?: boolean | { error?: (msg: any) => void; info?: (msg: any) => void }
23 html?: any
24 json?: any
25}
26
27export function errorHandler(_options: ErrorHandlerOptions = {}): ErrorRequestHandler {
28 const options = Object.assign({}, defaults, _options)
29
30 if (typeof options.html === 'undefined') {
31 options.html = {
32 401: path.resolve(options.public, '401.html'),
33 404: path.resolve(options.public, '404.html'),
34 default: defaultHtmlError
35 }
36 }
37
38 if (typeof options.json === 'undefined') {
39 options.json = {}
40 }
41
42 return function (error: any, req: Request, res: Response, next: NextFunction) {
43 // Set the error code for HTTP processing semantics
44 error.code = !isNaN(parseInt(error.code, 10)) ? parseInt(error.code, 10) : 500
45
46 // Log the error if it didn't come from a service method call
47 if (options.logger && typeof options.logger.error === 'function' && !res.hook) {
48 if (error.code >= 500) {
49 options.logger.error(error)
50 } else {
51 options.logger.info(error)
52 }
53 }
54
55 if (error.type !== 'FeathersError') {
56 const oldError = error
57
58 error = oldError.errors
59 ? new GeneralError(oldError.message, {
60 errors: oldError.errors
61 })
62 : new GeneralError(oldError.message)
63
64 if (oldError.stack) {
65 error.stack = oldError.stack
66 }
67 }
68
69 const formatter: { [key: string]: any } = {}
70
71 // If the developer passed a custom function for ALL html errors
72 if (typeof options.html === 'function') {
73 formatter['text/html'] = options.html
74 } else {
75 let file = options.html[error.code]
76 if (!file) {
77 file = options.html.default || defaultHtmlError
78 }
79 // If the developer passed a custom function for individual html errors
80 if (typeof file === 'function') {
81 formatter['text/html'] = file
82 } else {
83 formatter['text/html'] = function () {
84 res.set('Content-Type', 'text/html')
85 res.sendFile(file)
86 }
87 }
88 }
89
90 // If the developer passed a custom function for ALL json errors
91 if (typeof options.json === 'function') {
92 formatter['application/json'] = options.json
93 } else {
94 const handler = options.json[error.code] || options.json.default
95 // If the developer passed a custom function for individual json errors
96 if (typeof handler === 'function') {
97 formatter['application/json'] = handler
98 } else {
99 // Don't show stack trace if it is a 404 error
100 if (error.code === 404) {
101 error.stack = null
102 }
103
104 formatter['application/json'] = function () {
105 const output = Object.assign({}, error.toJSON())
106
107 if (process.env.NODE_ENV === 'production') {
108 delete output.stack
109 }
110
111 res.set('Content-Type', 'application/json')
112 res.json(output)
113 }
114 }
115 }
116
117 res.status(error.code)
118
119 const contentType = req.headers['content-type'] || ''
120 const accepts = req.headers.accept || ''
121
122 // by default just send back json
123 if (contentType.indexOf('json') !== -1 || accepts.indexOf('json') !== -1) {
124 formatter['application/json'](error, req, res, next)
125 } else if (options.html && (contentType.indexOf('html') !== -1 || accepts.indexOf('html') !== -1)) {
126 formatter['text/html'](error, req, res, next)
127 } else {
128 // TODO (EK): Maybe just return plain text
129 formatter['application/json'](error, req, res, next)
130 }
131 }
132}