Skip to content

Instantly share code, notes, and snippets.

@armanozak
Created December 16, 2020 11:17
Show Gist options
  • Save armanozak/4244997c545b058ee5b127d34cac1fe4 to your computer and use it in GitHub Desktop.
Save armanozak/4244997c545b058ee5b127d34cac1fe4 to your computer and use it in GitHub Desktop.
[Custom Error Constructors] How to use inheritance for better error handling #javascript #tip
// http-errors.js
export class HttpError extends Error {
code;
url;
constructor(code, url, message) {
super(message);
this.code = code;
this.url = url;
}
}
export class NotFoundError extends HttpError {
constructor(url) {
super(404, url, `${url} is not found.`);
}
}
export class ForbiddenError extends HttpError {
constructor(url) {
super(403, url, `No permision for ${url}.`);
}
}
export class UnauthorizedError extends HttpError {
constructor(url) {
super(401, url, `${url} requires authorization.`);
}
}
export const HTTP_ERRORS = new Map([
[401, UnauthorizedError],
[403, ForbiddenError],
[404, NotFoundError],
]);
import { HTTP_ERRORS, NotFoundError } from './http-errors';
fetch('https://jsonplaceholder.typicode.com/posts/0')
.then(detectHttpErrors)
.then(logJsonResponse)
.catch(handleError);
function detectHttpErrors(response) {
const DetectedError = HTTP_ERRORS.get(response.status);
if (DetectedError) throw new DetectedError(response.url);
return response;
}
async function logJsonResponse(response) {
return console.log(await response.json());
}
/* mock HTTP error handler */
function handleError(error) {
const isNotFound = error instanceof NotFoundError;
const log = isNotFound ? console.warn : console.error;
log(error.code, error.message);
/* console.warn will be used */
// 404 https://jsonplaceholder.typicode.com/posts/0 is not found.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment