deth
Version:
Ethereum node focused on Developer Experience
94 lines (93 loc) • 2.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const PathReporter_1 = require("io-ts/lib/PathReporter");
exports.errorHandler = function (err, req, res, next) {
let httpError;
if (err instanceof IOTSError) {
httpError = new BadRequestHttpError(err.details);
}
else if (err instanceof HttpError) {
httpError = err;
}
else {
httpError = new InternalHttpError();
}
if (httpError instanceof InternalHttpError) {
console.error('Internal error occured: ', err);
}
console.error(`<-- ERROR: ${httpError.code} - ${httpError.message} (${httpError.details})`);
const isRPC = req.method === 'POST' && req.url === '/';
if (isRPC) {
res.status(httpError.code);
res.json(httpErrorToRpcErrorPayload(req, httpError));
}
else {
res.status(httpError.code);
res.json(httpError.toBody());
}
};
class IOTSError extends Error {
constructor(details) {
super('IO-TS error');
this.details = PathReporter_1.PathReporter.report(details);
}
}
exports.IOTSError = IOTSError;
class HttpError extends Error {
constructor(code, msg, details) {
super(msg);
this.code = code;
this.details = details;
}
toBody() {
return {
error: {
status: this.code,
message: this.message,
details: this.details,
},
};
}
}
exports.HttpError = HttpError;
class BadRequestHttpError extends HttpError {
constructor(details) {
super(400, 'BadRequest', details);
}
}
exports.BadRequestHttpError = BadRequestHttpError;
class NotFoundHttpError extends HttpError {
constructor(details = []) {
super(404, 'NotFound');
this.details = details;
}
}
exports.NotFoundHttpError = NotFoundHttpError;
class InternalHttpError extends HttpError {
constructor() {
super(500, 'Internal');
}
}
exports.InternalHttpError = InternalHttpError;
function httpErrorToRpcStatus(err) {
switch (err.code) {
case 400:
return -32600;
case 404:
return -32601;
default:
return -32603;
}
}
function httpErrorToRpcErrorPayload(req, err) {
var _a;
return {
jsonrpc: '2.0',
id: (_a = req.body.id, (_a !== null && _a !== void 0 ? _a : null)),
error: {
code: httpErrorToRpcStatus(err),
message: err.message,
details: err.details,
},
};
}