Book Image

Server Side development with Node.js and Koa.js Quick Start Guide

By : Olayinka Omole
Book Image

Server Side development with Node.js and Koa.js Quick Start Guide

By: Olayinka Omole

Overview of this book

Every developer wants to build modular and scalable web applications. Modern versions of JavaScript have made this possible in Node.js, and Koa is a Node.js framework that makes it easy. This book is the ideal introduction for JavaScript developers who want to create scalable server side applications using Node.js and Koa.js. The book shows you how Koa can be used to start projects from scratch, register custom and existing middleware, read requests, and send responses to users. We will explore the core concepts in Koa, such as error handling, logging, and request and response handling. We will dive into new concepts in JavaScript development, and see how paradigms such as async/await help with modern Node.js application development. By the end of this book, you will be building robust web applications in Koa using modern development paradigms and techniques of Node.js development.
Table of Contents (8 chapters)

Writing error handlers

To register custom error handlers in Koa, we simply need to define middleware with a try... catch statement to capture the errors, then send responses back to the client. This should be done at the top of the stack.

We can define error handlers based on various requirements to handle different types of errors for different types of clients. These error handlers can be used independently or combined, depending on the needs of the application. Let's define a set of error handlers and register them in our application:

const jsonErrorHandler = async (ctx, next) => {
try {
await next();
} catch (err) {
const isJson = ctx.get('Accept') === 'application/json';
if (isJson) {
ctx.body = {
error: 'An error just occurred'
}
} else {
throw err;
}
}
}

app.use(jsonErrorHandler);

The first error...