backend: fix lint "no-throw-literal"

This commit is contained in:
Johann150 2022-08-04 11:00:02 +02:00 committed by ThatOneCalculator
parent d6faae48f2
commit 49686050cc
18 changed files with 35 additions and 35 deletions

View file

@ -112,13 +112,12 @@ function loadConfigBoot(): Config {
try {
config = loadConfig();
} catch (exception) {
if (typeof exception === 'string') {
configLogger.error(exception);
process.exit(1);
}
if (exception.code === 'ENOENT') {
configLogger.error('Configuration file not found', null, true);
process.exit(1);
} else if (e instanceof Error) {
configLogger.error(e.message);
process.exit(1);
}
throw exception;
}

View file

@ -57,6 +57,6 @@ function tryCreateUrl(url: string) {
try {
return new URL(url);
} catch (e) {
throw `url="${url}" is not a valid URL.`;
throw new Error(`url="${url}" is not a valid URL.`);
}
}

View file

@ -5,23 +5,23 @@ import config from '@/config/index.js';
export async function verifyRecaptcha(secret: string, response: string) {
const result = await getCaptchaResponse('https://www.recaptcha.net/recaptcha/api/siteverify', secret, response).catch(e => {
throw `recaptcha-request-failed: ${e}`;
throw new Error(`recaptcha-request-failed: ${e.message}`);
});
if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes']?.join(', ') : '';
throw `recaptcha-failed: ${errorCodes}`;
throw new Error(`recaptcha-failed: ${errorCodes}`);
}
}
export async function verifyHcaptcha(secret: string, response: string) {
const result = await getCaptchaResponse('https://hcaptcha.com/siteverify', secret, response).catch(e => {
throw `hcaptcha-request-failed: ${e}`;
throw new Error(`hcaptcha-request-failed: ${e.message}`);
});
if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes']?.join(', ') : '';
throw `hcaptcha-failed: ${errorCodes}`;
throw new Error(`hcaptcha-failed: ${errorCodes}`);
}
}
@ -46,11 +46,11 @@ async function getCaptchaResponse(url: string, secret: string, response: string)
//timeout: 10 * 1000,
agent: getAgentByUrl,
}).catch(e => {
throw `${e.message || e}`;
throw new Error(`${e.message || e}`);
});
if (!res.ok) {
throw `${res.status}`;
throw new Error(`${res.status}`);
}
return await res.json() as CaptchaResponse;

View file

@ -13,7 +13,7 @@ export function dateUTC(time: number[]): Date {
: time.length === 7 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5], time[6])
: null;
if (!d) throw 'wrong number of arguments';
if (!d) throw new Error('wrong number of arguments');
return new Date(d);
}

View file

@ -55,7 +55,7 @@ export async function importBlocking(job: Bull.Job<DbUserImportJobData>, done: a
}
if (target == null) {
throw `cannot resolve user: @${username}@${host}`;
throw new Error(`cannot resolve user: @${username}@${host}`);
}
// skip myself

View file

@ -55,7 +55,7 @@ export async function importFollowing(job: Bull.Job<DbUserImportJobData>, done:
}
if (target == null) {
throw `cannot resolve user: @${username}@${host}`;
throw new Error(`cannot resolve user: @${username}@${host}`);
}
// skip myself

View file

@ -56,7 +56,7 @@ export async function importMuting(job: Bull.Job<DbUserImportJobData>, done: any
}
if (target == null) {
throw `cannot resolve user: @${username}@${host}`;
throw new Error(`cannot resolve user: @${username}@${host}`);
}
// skip myself

View file

@ -93,7 +93,7 @@ export default async (job: Bull.Job<DeliverJobData>) => {
}
// 5xx etc.
throw `${res.statusCode} ${res.statusMessage}`;
throw new Error(`${res.statusCode} ${res.statusMessage}`);
} else {
// DNS error, socket error, timeout ...
throw res;

View file

@ -67,7 +67,7 @@ export default async (job: Bull.Job<InboxJobData>): Promise<string> => {
if (e.isClientError) {
return `skip: Ignored deleted actors on both ends ${activity.actor} - ${e.statusCode}`;
}
throw `Error in actor ${activity.actor} - ${e.statusCode || e}`;
throw new Error(`Error in actor ${activity.actor} - ${e.statusCode || e}`);
}
}
}

View file

@ -50,7 +50,7 @@ export default async (job: Bull.Job<WebhookDeliverJobData>) => {
}
// 5xx etc.
throw `${res.statusCode} ${res.statusMessage}`;
throw new Error(`${res.statusCode} ${res.statusMessage}`);
} else {
// DNS error, socket error, timeout ...
throw res;

View file

@ -85,7 +85,7 @@ export class LdSignature {
private getLoader() {
return async (url: string): Promise<any> => {
if (!url.match('^https?\:\/\/')) throw `Invalid URL ${url}`;
if (!url.match('^https?\:\/\/')) throw new Error(`Invalid URL ${url}`);
if (this.preLoad) {
if (url in CONTEXTS) {
@ -118,7 +118,7 @@ export class LdSignature {
agent: u => u.protocol === 'http:' ? httpAgent : httpsAgent,
}).then(res => {
if (!res.ok) {
throw `${res.status} ${res.statusText}`;
throw new Error(`${res.status} ${res.statusText}`);
} else {
return res.json();
}

View file

@ -189,7 +189,7 @@ export async function createNote(value: string | IObject, resolver?: Resolver, s
quote = results.filter((x): x is { status: 'ok', res: Note | null } => x.status === 'ok').map(x => x.res).find(x => x);
if (!quote) {
if (results.some(x => x.status === 'temperror')) {
throw 'quote resolve failed';
throw new Error('quote resolve failed');
}
}
}
@ -276,7 +276,7 @@ export async function resolveNote(value: string | IObject, resolver?: Resolver):
// ブロックしてたら中断
const meta = await fetchMeta();
if (meta.blockedHosts.includes(extractDbHost(uri))) throw { statusCode: 451 };
if (meta.blockedHosts.includes(extractDbHost(uri))) throw new StatusError('host blocked', 451, `host ${extractDbHost(uri)} is blocked`);
const unlock = await getApLock(uri);

View file

@ -27,6 +27,7 @@ export const meta = {
format: 'id',
},
inbox: {
description: 'URL of the inbox, must be a https scheme URL',
type: 'string',
optional: false, nullable: false,
format: 'url',
@ -56,7 +57,7 @@ export const paramDef = {
// eslint-disable-next-line import/no-default-export
export default define(meta, paramDef, async (ps, user) => {
try {
if (new URL(ps.inbox).protocol !== 'https:') throw 'https only';
if (new URL(ps.inbox).protocol !== 'https:') throw new Error('https only');
} catch {
throw new ApiError(meta.errors.invalidUrl);
}

View file

@ -68,7 +68,7 @@ async function unFollowAll(follower: User) {
});
if (followee == null) {
throw `Cant find followee ${following.followeeId}`;
throw new Error(`Cant find followee ${following.followeeId}`);
}
await deleteFollowing(follower, followee, true);

View file

@ -87,14 +87,14 @@ export default define(meta, paramDef, async (ps, me) => {
try {
if (ps.tag) {
if (!safeForSql(ps.tag)) throw 'Injection';
if (!safeForSql(ps.tag)) throw new Error('Injection');
query.andWhere(`'{"${normalizeForSearch(ps.tag)}"}' <@ note.tags`);
} else {
query.andWhere(new Brackets(qb => {
for (const tags of ps.query!) {
qb.orWhere(new Brackets(qb => {
for (const tag of tags) {
if (!safeForSql(tag)) throw 'Injection';
if (!safeForSql(tag)) throw new Error('Injection');
qb.andWhere(`'{"${normalizeForSearch(tag)}"}' <@ note.tags`);
}
}));
@ -102,7 +102,7 @@ export default define(meta, paramDef, async (ps, me) => {
}));
}
} catch (e) {
if (e === 'Injection') return [];
if (e.message === 'Injection') return [];
throw e;
}

View file

@ -22,7 +22,7 @@ export const paramDef = {
// eslint-disable-next-line import/no-default-export
export default define(meta, paramDef, async (ps, user) => {
if (process.env.NODE_ENV !== 'test') throw 'NODE_ENV is not a test';
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV is not a test');
await resetDb();

View file

@ -94,14 +94,14 @@ async function fetchNodeinfo(instance: Instance): Promise<NodeInfo> {
const wellknown = await getJson('https://' + instance.host + '/.well-known/nodeinfo')
.catch(e => {
if (e.statusCode === 404) {
throw 'No nodeinfo provided';
throw new Error('No nodeinfo provided');
} else {
throw e.statusCode || e.message;
throw new Error(e.statusCode || e.message);
}
}) as Record<string, unknown>;
if (wellknown.links == null || !Array.isArray(wellknown.links)) {
throw 'No wellknown links';
throw new Error('No wellknown links');
}
const links = wellknown.links as any[];
@ -112,19 +112,19 @@ async function fetchNodeinfo(instance: Instance): Promise<NodeInfo> {
const link = lnik2_1 || lnik2_0 || lnik1_0;
if (link == null) {
throw 'No nodeinfo link provided';
throw new Error('No nodeinfo link provided');
}
const info = await getJson(link.href)
.catch(e => {
throw e.statusCode || e.message;
throw new Error(e.statusCode || e.message);
});
logger.succ(`Successfuly fetched nodeinfo of ${instance.host}`);
return info as NodeInfo;
} catch (e) {
logger.error(`Failed to fetch nodeinfo of ${instance.host}: ${e}`);
logger.error(`Failed to fetch nodeinfo of ${instance.host}: ${e.message}`);
throw e;
}

View file

@ -47,7 +47,7 @@ export async function removeRelay(inbox: string) {
});
if (relay == null) {
throw 'relay not found';
throw new Error('relay not found');
}
const relayActor = await getRelayActor();