Skip to content
This repository has been archived by the owner on Aug 26, 2022. It is now read-only.

feature:Return an error instance that extends the built-in Error object #49

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions pbjs-twirp/twirp.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
import {AxiosError, AxiosInstance, AxiosResponse} from 'axios';
import {Message, Method, rpc, RPCImpl, RPCImplCallback} from 'protobufjs';

interface TwirpError {
interface InternalTwirpError {
code: string;
msg: string;
meta?:{[key:string]:string};
}

class TwirpError extends Error {
code: string;
meta?: {[key: string]: string};

constructor(message: string, twirpError: InternalTwirpError) {
super(message);
this.name = this.constructor.name;
Object.setPrototypeOf(this, new.target.prototype);

this.code = twirpError.code;
this.meta = twirpError.meta;
}
}

const getTwirpError = (err: AxiosError): TwirpError => {
const resp = err.response;
let twirpError = {
Expand All @@ -19,7 +33,7 @@ const getTwirpError = (err: AxiosError): TwirpError => {
const headers = resp.headers;
const data = resp.data;

if (headers['content-type'] === 'application/json') {
if (headers['content-type'].match(/^(?=.*application\/json).*$/)) {
s-hakase marked this conversation as resolved.
Show resolved Hide resolved
let s = data.toString();

if (s === "[object ArrayBuffer]") {
Expand All @@ -34,7 +48,7 @@ const getTwirpError = (err: AxiosError): TwirpError => {
}
}

return twirpError;
return new TwirpError(twirpError.msg, twirpError);
};

export const createTwirpAdapter = (axios: AxiosInstance, methodLookup: (fn: any) => string): RPCImpl => {
Expand Down