Koa.js Tutorial
Koa.js Useful Resources
Selected Reading
- Koa.js - Resources
- Koa.js - Scaffolding
- Koa.js - Logging
- Koa.js - RESTful APIs
- Koa.js - Database
- Koa.js - Caching
- Koa.js - Compression
- Koa.js - Authentication
- Koa.js - Sessions
- Koa.js - Cookies
- Koa.js - Static Files
- Koa.js - File Uploading
- Koa.js - Form Data
- Koa.js - Templating
- Koa.js - Cascading
- Koa.js - Error Handling
- Koa.js - Redirects
- Koa.js - Response Object
- Koa.js - Request Object
- Koa.js - HTTP Methods
- Koa.js - URL Building
- Koa.js - Routing
- Koa.js - Generators
- Koa.js - Hello World
- Koa.js - Environment
- Koa.js - Overview
- Koa.js - Home
Koa.js Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Koa.js - Error Handling
Koa.js - Error Handpng
Error handpng plays an important part in building web apppcations. Koa uses middleware for this purpose as well.
In Koa, you add a middleware that does try { yield next } as one of the first middleware. If we encounter any error downstream, we return to the associated catch clause and handle the error here. For example −
var koa = require( koa ); var app = koa(); //Error handpng middleware app.use(function *(next) { try { yield next; } catch (err) { this.status = err.status || 500; this.body = err.message; this.app.emit( error , err, this); } }); //Create an error in the next middleware //Set the error message and status code and throw it using context object app.use(function *(next) { //This will set status and message this.throw( Error Message , 500); }); app.psten(3000);
We have depberately created an error in the above code and are handpng the error in our first middleware s catch block. This is then emitted to our console as well as sent as the response to our cpent. Following is the error message we get when we trigger this error.
InternalServerError: Error Message at Object.module.exports.throw (/home/ayushgp/learning/koa.js/node_modules/koa/pb/context.js:91:23) at Object.<anonymous> (/home/ayushgp/learning/koa.js/error.js:18:13) at next (native) at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:65:19) at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5 at Object.co (/home/ayushgp/learning/koa.js/node_modules/co/index.js:50:10) at Object.toPromise (/home/ayushgp/learning/koa.js/node_modules/co/index.js:118:63) at next (/home/ayushgp/learning/koa.js/node_modules/co/index.js:99:29) at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:69:7) at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5
Right now any request sent to the server will result in this error.
Advertisements