title: Exception Handling

Exception Capture

Taking benefits from framework asynchronous support, all exceptions can be caught by try catch.

With those features, you can take following implementation as reference:

  1. // app/service/test.js
  2. try {
  3. const res = await this.ctx.curl('http://eggjs.com/api/echo', { dataType: 'json' });
  4. if (res.status !== 200) throw new Error('response status is not 200');
  5. return res.data;
  6. } catch (err) {
  7. this.logger.error(err);
  8. return {};
  9. }

Generally, you can use try catch to catch exceptions. However, some implementations may break this mechanism down. Imaging that await makes generators run in order just like a chain. What will happen if one of them jumpoff the chain? The following code can help you realize the imagination:

  1. // app/controller/home.js
  2. class HomeController extends Controller {
  3. async buy () {
  4. const request = {};
  5. const config = await ctx.service.trade.buy(request);
  6. // checking the deal and don't block current request
  7. setImmediate(() => {
  8. ctx.service.trade.check(request).catch(err => ctx.logger.error(err));
  9. });
  10. }
  11. }

In this case, you may find that the exceptions in setImmediate will be swallowed because the scope breaks the chain, although egg already handled exceptions externally.

Above scene is also considered. To catch the exception inside the scope, You can invoke helper method ctx.runInBackground(scope) to wrap the chain back. Now, the exceptions will be detected and caught.

  1. class HomeController extends Controller {
  2. async buy () {
  3. const request = {};
  4. const config = await ctx.service.trade.buy(request);
  5. // checking the deal and don't block current request
  6. ctx.runInBackground(async () => {
  7. // Exceptions thrown here will be caught in background and printed into log.
  8. await ctx.service.trade.check(request);
  9. });
  10. }
  11. }

For convenience of locating problems, exceptions must be guaranteed to be Error object or object based on Error object, which offers a trace of which functions were called.

Egg takes charge of exceptions

egg-onerror, one of Egg’s plugin, handles all exceptions thrown in Middleware, Controller and Service, and returns the error as response based on “Accept” in request header field.

Accept ENV errorPageUrl response
HTML & TEXT local & unittest - onerror built-in error page
HTML & TEXT others YES redirect to errorPageUrl
HTML & TEXT others NO onerror built-in error page(simple, not recommended)
JSON & JSONP local & unittest - JSON Object or JSONP response body with details
JSON & JSONP others - JSON object or JSONP response body without details

errorPageUrl

Redirecting to your customized error page by setting errorPageUrl in onerror plugin.

onerror config in config/config.default.js:

  1. module.exports = {
  2. onerror: {
  3. errorPageUrl: '/50x.html',
  4. },
  5. };

Create your universal exception handler

Once the default handler no longer meet your needs, you still can customize your owner error handler by onerror’s configurations.

  1. // config/config.default.js
  2. module.exports = {
  3. onerror: {
  4. all(err, ctx) {
  5. // Define an error handler for all type of Response.
  6. // Once config.all present, other type of error handers will be ignored.
  7. ctx.body = 'error';
  8. ctx.status = 500;
  9. },
  10. html(err, ctx) {
  11. // html hander
  12. ctx.body = '<h3>error</h3>';
  13. ctx.status = 500;
  14. },
  15. json(err, ctx) {
  16. // json hander
  17. ctx.body = { message: 'error' };
  18. ctx.status = 500;
  19. },
  20. jsonp(err, ctx) {
  21. // Generally, we don't need to customize jsonp error handler.
  22. // It will call json error handler and wrap to jsonp type response.
  23. },
  24. };

404

Egg won’t take NOT FOUND from back-end as exception. Instead, if NOT FOUND is emitted without a body, it will return the following JSON object as default response.

identified as JSON:

  1. {
  2. "message": "Not Found"
  3. }

identified as HTML:

  1. <h1>404 Not Found</h1>

Overriding default 404 page to the one you want:

  1. // config/config.default.js
  2. module.exports = {
  3. notfound: {
  4. pageUrl: '/404.html',
  5. },
  6. };

Customize 404 Response

If you want a customized 404 response, you only need to create a middleware to handle it once, just like handling exceptions above.

  1. // app/middleware/notfound_handler.js
  2. module.exports = () => {
  3. return async function notFoundHandler(ctx, next) {
  4. await next();
  5. if (ctx.status === 404 && !ctx.body) {
  6. if (ctx.acceptJSON) {
  7. ctx.body = { error: 'Not Found' };
  8. } else {
  9. ctx.body = '<h1>Page Not Found</h1>';
  10. }
  11. }
  12. };
  13. };

Adding yours to middleware in config:

  1. // config/config.default.js
  2. module.exports = {
  3. middleware: [ 'notfoundHandler' ],
  4. };