fix: Use HttpErrors instead of Errors

This commit is contained in:
Joachim Van Herwegen 2021-04-08 14:33:25 +02:00
parent a00de24ec0
commit 218c8f4662
7 changed files with 18 additions and 9 deletions

View File

@ -1,4 +1,5 @@
import type { HttpRequest } from '../../server/HttpRequest'; import type { HttpRequest } from '../../server/HttpRequest';
import { InternalServerError } from '../../util/errors/InternalServerError';
import type { Operation } from '../operations/Operation'; import type { Operation } from '../operations/Operation';
import type { BodyParser } from './BodyParser'; import type { BodyParser } from './BodyParser';
import type { MetadataExtractor } from './metadata/MetadataExtractor'; import type { MetadataExtractor } from './metadata/MetadataExtractor';
@ -34,7 +35,7 @@ export class BasicRequestParser extends RequestParser {
public async handle(request: HttpRequest): Promise<Operation> { public async handle(request: HttpRequest): Promise<Operation> {
const { method } = request; const { method } = request;
if (!method) { if (!method) {
throw new Error('No method specified on the HTTP request'); throw new InternalServerError('No method specified on the HTTP request');
} }
const target = await this.targetExtractor.handleSafe({ request }); const target = await this.targetExtractor.handleSafe({ request });
const preferences = await this.preferenceParser.handleSafe({ request }); const preferences = await this.preferenceParser.handleSafe({ request });

View File

@ -1,5 +1,7 @@
import type { TLSSocket } from 'tls'; import type { TLSSocket } from 'tls';
import type { HttpRequest } from '../../server/HttpRequest'; import type { HttpRequest } from '../../server/HttpRequest';
import { BadRequestHttpError } from '../../util/errors/BadRequestHttpError';
import { InternalServerError } from '../../util/errors/InternalServerError';
import { parseForwarded } from '../../util/HeaderUtil'; import { parseForwarded } from '../../util/HeaderUtil';
import { toCanonicalUriPath } from '../../util/PathUtil'; import { toCanonicalUriPath } from '../../util/PathUtil';
import type { ResourceIdentifier } from '../representation/ResourceIdentifier'; import type { ResourceIdentifier } from '../representation/ResourceIdentifier';
@ -18,7 +20,7 @@ export class OriginalUrlExtractor extends TargetExtractor {
public async handle({ request: { url, connection, headers }}: { request: HttpRequest }): Promise<ResourceIdentifier> { public async handle({ request: { url, connection, headers }}: { request: HttpRequest }): Promise<ResourceIdentifier> {
if (!url) { if (!url) {
throw new Error('Missing URL'); throw new InternalServerError('Missing URL');
} }
// Extract host and protocol (possibly overridden by the Forwarded/X-Forwarded-* header) // Extract host and protocol (possibly overridden by the Forwarded/X-Forwarded-* header)
@ -36,10 +38,10 @@ export class OriginalUrlExtractor extends TargetExtractor {
// Perform a sanity check on the host // Perform a sanity check on the host
if (!host) { if (!host) {
throw new Error('Missing Host header'); throw new BadRequestHttpError('Missing Host header');
} }
if (/[/\\*]/u.test(host)) { if (/[/\\*]/u.test(host)) {
throw new Error(`The request has an invalid Host header: ${host}`); throw new BadRequestHttpError(`The request has an invalid Host header: ${host}`);
} }
// URL object applies punycode encoding to domain // URL object applies punycode encoding to domain

View File

@ -1,6 +1,7 @@
import { DataFactory, Store } from 'n3'; import { DataFactory, Store } from 'n3';
import type { BlankNode, Literal, NamedNode, Quad, Term } from 'rdf-js'; import type { BlankNode, Literal, NamedNode, Quad, Term } from 'rdf-js';
import { getLoggerFor } from '../../logging/LogUtil'; import { getLoggerFor } from '../../logging/LogUtil';
import { InternalServerError } from '../../util/errors/InternalServerError';
import { toSubjectTerm, toObjectTerm, toCachedNamedNode, isTerm } from '../../util/TermUtil'; import { toSubjectTerm, toObjectTerm, toCachedNamedNode, isTerm } from '../../util/TermUtil';
import { CONTENT_TYPE, CONTENT_TYPE_TERM } from '../../util/Vocabularies'; import { CONTENT_TYPE, CONTENT_TYPE_TERM } from '../../util/Vocabularies';
import type { ResourceIdentifier } from './ResourceIdentifier'; import type { ResourceIdentifier } from './ResourceIdentifier';
@ -265,7 +266,9 @@ export class RepresentationMetadata {
} }
if (terms.length > 1) { if (terms.length > 1) {
this.logger.error(`Multiple results for ${typeof predicate === 'string' ? predicate : predicate.value}`); this.logger.error(`Multiple results for ${typeof predicate === 'string' ? predicate : predicate.value}`);
throw new Error(`Multiple results for ${typeof predicate === 'string' ? predicate : predicate.value}`); throw new InternalServerError(
`Multiple results for ${typeof predicate === 'string' ? predicate : predicate.value}`,
);
} }
return terms[0]; return terms[0];
} }

View File

@ -3,6 +3,7 @@ import arrayifyStream from 'arrayify-stream';
import type { NamedNode } from 'rdf-js'; import type { NamedNode } from 'rdf-js';
import { RepresentationMetadata } from '../../ldp/representation/RepresentationMetadata'; import { RepresentationMetadata } from '../../ldp/representation/RepresentationMetadata';
import type { ResourceIdentifier } from '../../ldp/representation/ResourceIdentifier'; import type { ResourceIdentifier } from '../../ldp/representation/ResourceIdentifier';
import { InternalServerError } from '../../util/errors/InternalServerError';
import { NotFoundHttpError } from '../../util/errors/NotFoundHttpError'; import { NotFoundHttpError } from '../../util/errors/NotFoundHttpError';
import type { Guarded } from '../../util/GuardedStream'; import type { Guarded } from '../../util/GuardedStream';
import type { IdentifierStrategy } from '../../util/identifiers/IdentifierStrategy'; import type { IdentifierStrategy } from '../../util/identifiers/IdentifierStrategy';
@ -121,7 +122,7 @@ export class InMemoryDataAccessor implements DataAccessor {
throw new NotFoundHttpError(); throw new NotFoundHttpError();
} }
if (this.isDataEntry(parent)) { if (this.isDataEntry(parent)) {
throw new Error('Invalid path.'); throw new InternalServerError('Invalid path.');
} }
} }

View File

@ -1,5 +1,6 @@
import type { Representation } from '../../ldp/representation/Representation'; import type { Representation } from '../../ldp/representation/Representation';
import { getLoggerFor } from '../../logging/LogUtil'; import { getLoggerFor } from '../../logging/LogUtil';
import { InternalServerError } from '../../util/errors/InternalServerError';
import { matchesMediaType } from './ConversionUtil'; import { matchesMediaType } from './ConversionUtil';
import type { RepresentationConverterArgs } from './RepresentationConverter'; import type { RepresentationConverterArgs } from './RepresentationConverter';
import { TypedRepresentationConverter } from './TypedRepresentationConverter'; import { TypedRepresentationConverter } from './TypedRepresentationConverter';
@ -79,7 +80,7 @@ export class ChainedConverter extends TypedRepresentationConverter {
if (bestMatch.weight === 0) { if (bestMatch.weight === 0) {
this.logger.warn(`No match found between ${leftKeys} and ${rightKeys}`); this.logger.warn(`No match found between ${leftKeys} and ${rightKeys}`);
throw new Error(`No match found between ${leftKeys} and ${rightKeys}`); throw new InternalServerError(`No match found between ${leftKeys} and ${rightKeys}`);
} }
this.logger.debug(`${bestMatch.type} is the best match between ${leftKeys} and ${rightKeys}`); this.logger.debug(`${bestMatch.type} is the best match between ${leftKeys} and ${rightKeys}`);

View File

@ -2,6 +2,7 @@ import type { ResourceIdentifier } from '../../ldp/representation/ResourceIdenti
import { getLoggerFor } from '../../logging/LogUtil'; import { getLoggerFor } from '../../logging/LogUtil';
import { APPLICATION_OCTET_STREAM } from '../../util/ContentTypes'; import { APPLICATION_OCTET_STREAM } from '../../util/ContentTypes';
import { BadRequestHttpError } from '../../util/errors/BadRequestHttpError'; import { BadRequestHttpError } from '../../util/errors/BadRequestHttpError';
import { InternalServerError } from '../../util/errors/InternalServerError';
import { NotFoundHttpError } from '../../util/errors/NotFoundHttpError'; import { NotFoundHttpError } from '../../util/errors/NotFoundHttpError';
import { import {
decodeUriPathComponents, decodeUriPathComponents,
@ -98,7 +99,7 @@ export class BaseFileIdentifierMapper implements FileIdentifierMapper {
public async mapFilePathToUrl(filePath: string, isContainer: boolean): Promise<ResourceLink> { public async mapFilePathToUrl(filePath: string, isContainer: boolean): Promise<ResourceLink> {
if (!filePath.startsWith(this.rootFilepath)) { if (!filePath.startsWith(this.rootFilepath)) {
this.logger.error(`Trying to access file ${filePath} outside of ${this.rootFilepath}`); this.logger.error(`Trying to access file ${filePath} outside of ${this.rootFilepath}`);
throw new Error(`File ${filePath} is not part of the file storage at ${this.rootFilepath}`); throw new InternalServerError(`File ${filePath} is not part of the file storage at ${this.rootFilepath}`);
} }
const relative = filePath.slice(this.rootFilepath.length); const relative = filePath.slice(this.rootFilepath.length);
let url: string; let url: string;

View File

@ -48,7 +48,7 @@ export class WaterfallHandler<TIn, TOut> implements AsyncHandler<TIn, TOut> {
handler = await this.findHandler(input); handler = await this.findHandler(input);
} catch { } catch {
this.logger.warn('All handlers failed. This might be the consequence of calling handle before canHandle.'); this.logger.warn('All handlers failed. This might be the consequence of calling handle before canHandle.');
throw new Error('All handlers failed'); throw new InternalServerError('All handlers failed');
} }
return handler.handle(input); return handler.handle(input);