|
| 1 | +# Error Handling |
| 2 | + |
| 3 | +## Try-Catch |
| 4 | + |
| 5 | + Using generators means that you can try-catch `next`. For example, |
| 6 | + this example prepends all error messages with "Error: " |
| 7 | + |
| 8 | + ```js |
| 9 | + app.use(function*(next){ |
| 10 | + try { |
| 11 | + yield next; |
| 12 | + } catch (error) { |
| 13 | + error.message = 'Error: ' + error.message; |
| 14 | + throw error; |
| 15 | + } |
| 16 | + }); |
| 17 | + ``` |
| 18 | + |
| 19 | +### Default Error Handler |
| 20 | + |
| 21 | + The default error handler is essentially a try-catch at |
| 22 | + the very beginning of the middleware chain. To use a |
| 23 | + different error handler, simply put another try-catch at |
| 24 | + the beginning of the middleware chain, and handle the error |
| 25 | + there. However, the default error handler is good enough for |
| 26 | + most use cases. It will use a status code of `err.status`, |
| 27 | + or by default 500. If `err.expose` is true, then `err.message` |
| 28 | + will be the reply. Otherwise, a message generated from the |
| 29 | + error code will be used (e.g. for the code 500 the message |
| 30 | + "Internal Server Error" will be used). All headers will be |
| 31 | + cleared from the request, but any headers in `err.headers` |
| 32 | + will then be set. You can use a try-catch, as specified |
| 33 | + above, to add a header to this list. |
| 34 | + |
| 35 | +## The Error Event |
| 36 | + |
| 37 | + Error handlers can be specified with `app.on('error')`. |
| 38 | + If no error handler is specified, a default error handler |
| 39 | + is used. Error handlers recieve all errors that make their |
| 40 | + way back through the middleware chain, if an error is caught |
| 41 | + and not thrown again, it will not be handled by the error |
| 42 | + handler. If not error event handler is specified, then |
| 43 | + `app.onerror` will be used, which simply log the error if |
| 44 | + `error.expose` is true and `app.silent` is false. |
0 commit comments