Skip to content

Full Toolkit for Next-Level Domain Analysis

Add user-facing error handling with structured error messages πŸ’β€β™‚οΈπŸ§© (#59)

Felix Wotschofskyeb344b025f9c
diff --git a/app/error.tsx b/app/error.tsx
index 849ad59..35dec3d 100644
--- a/app/error.tsx
+++ b/app/error.tsx
@@ -1,25 +1,20 @@
'use client';
-import { type FC, useEffect } from 'react';
+import type { FC } from 'react';
+
+import { BoundaryError } from '@/components/boundary-error';
type GlobalErrorProps = {
error: Error & { digest?: string };
- reset: () => void;
+ unstable_retry: () => void;
};
-const GlobalError: FC<GlobalErrorProps> = ({ error }) => {
- useEffect(() => {
- console.error(error);
- }, [error]);
-
- return (
- <div className="mt-12 flex flex-col items-center gap-2">
- <h2>Something went VERY wrong!</h2>
- <p className="mt-2 text-center text-sm text-zinc-500 dark:text-zinc-400">
- Digest: {error.digest}
- </p>
- </div>
- );
-};
+const GlobalError: FC<GlobalErrorProps> = ({ error, unstable_retry }) => (
+ <BoundaryError
+ error={error}
+ retry={unstable_retry}
+ fallbackTitle="Something went VERY wrong!"
+ />
+);
export default GlobalError;
diff --git a/app/lookup/[domain]/certs/error.tsx b/app/lookup/[domain]/certs/error.tsx
index c3caef9..a3dad6b 100644
--- a/app/lookup/[domain]/certs/error.tsx
+++ b/app/lookup/[domain]/certs/error.tsx
@@ -1,25 +1,16 @@
'use client';
-import { type FC, useEffect } from 'react';
+import type { FC } from 'react';
+
+import { BoundaryError } from '@/components/boundary-error';
type CertsErrorProps = {
error: Error & { digest?: string };
- reset: () => void;
+ unstable_retry: () => void;
};
-const CertsError: FC<CertsErrorProps> = ({ error }) => {
- useEffect(() => {
- console.error(error);
- }, [error]);
-
- return (
- <div className="mt-12 flex flex-col items-center gap-2">
- <h2>Something went wrong!</h2>
- <p className="mt-2 text-center text-sm text-zinc-500 dark:text-zinc-400">
- Digest: {error.digest}
- </p>
- </div>
- );
-};
+const CertsError: FC<CertsErrorProps> = ({ error, unstable_retry }) => (
+ <BoundaryError error={error} retry={unstable_retry} />
+);
export default CertsError;
diff --git a/app/lookup/[domain]/error.tsx b/app/lookup/[domain]/error.tsx
index b6b56f1..5ad6b2b 100644
--- a/app/lookup/[domain]/error.tsx
+++ b/app/lookup/[domain]/error.tsx
@@ -1,25 +1,16 @@
'use client';
-import { type FC, useEffect } from 'react';
+import type { FC } from 'react';
+
+import { BoundaryError } from '@/components/boundary-error';
type DomainErrorProps = {
error: Error & { digest?: string };
- reset: () => void;
+ unstable_retry: () => void;
};
-const DomainError: FC<DomainErrorProps> = ({ error }) => {
- useEffect(() => {
- console.error(error);
- }, [error]);
-
- return (
- <div className="mt-12 flex flex-col items-center gap-2">
- <h2>Something went wrong!</h2>
- <p className="mt-2 text-center text-sm text-zinc-500 dark:text-zinc-400">
- Digest: {error.digest}
- </p>
- </div>
- );
-};
+const DomainError: FC<DomainErrorProps> = ({ error, unstable_retry }) => (
+ <BoundaryError error={error} retry={unstable_retry} />
+);
export default DomainError;
diff --git a/app/lookup/[domain]/map/error.tsx b/app/lookup/[domain]/map/error.tsx
index 5f3e061..5d25aea 100644
--- a/app/lookup/[domain]/map/error.tsx
+++ b/app/lookup/[domain]/map/error.tsx
@@ -1,25 +1,16 @@
'use client';
-import { type FC, useEffect } from 'react';
+import type { FC } from 'react';
+
+import { BoundaryError } from '@/components/boundary-error';
type MapErrorProps = {
error: Error & { digest?: string };
- reset: () => void;
+ unstable_retry: () => void;
};
-const MapError: FC<MapErrorProps> = ({ error }) => {
- useEffect(() => {
- console.error(error);
- }, [error]);
-
- return (
- <div className="mt-12 flex flex-col items-center gap-2">
- <h2>Something went wrong!</h2>
- <p className="mt-2 text-center text-sm text-zinc-500 dark:text-zinc-400">
- Digest: {error.digest}
- </p>
- </div>
- );
-};
+const MapError: FC<MapErrorProps> = ({ error, unstable_retry }) => (
+ <BoundaryError error={error} retry={unstable_retry} />
+);
export default MapError;
diff --git a/app/lookup/[domain]/subdomains/error.tsx b/app/lookup/[domain]/subdomains/error.tsx
index db7f08a..479389a 100644
--- a/app/lookup/[domain]/subdomains/error.tsx
+++ b/app/lookup/[domain]/subdomains/error.tsx
@@ -1,25 +1,17 @@
'use client';
-import { type FC, useEffect } from 'react';
+import type { FC } from 'react';
+
+import { BoundaryError } from '@/components/boundary-error';
type SubdomainsErrorProps = {
error: Error & { digest?: string };
- reset: () => void;
+ unstable_retry: () => void;
};
-const SubdomainsError: FC<SubdomainsErrorProps> = ({ error }) => {
- useEffect(() => {
- console.error(error);
- }, [error]);
-
- return (
- <div className="mt-12 flex flex-col items-center gap-2">
- <h2>Something went wrong!</h2>
- <p className="mt-2 text-center text-sm text-zinc-500 dark:text-zinc-400">
- Digest: {error.digest}
- </p>
- </div>
- );
-};
+const SubdomainsError: FC<SubdomainsErrorProps> = ({
+ error,
+ unstable_retry,
+}) => <BoundaryError error={error} retry={unstable_retry} />;
export default SubdomainsError;
diff --git a/app/lookup/[domain]/whois/error.tsx b/app/lookup/[domain]/whois/error.tsx
index 727cd27..e03c4e8 100644
--- a/app/lookup/[domain]/whois/error.tsx
+++ b/app/lookup/[domain]/whois/error.tsx
@@ -1,25 +1,16 @@
'use client';
-import { type FC, useEffect } from 'react';
+import type { FC } from 'react';
+
+import { BoundaryError } from '@/components/boundary-error';
type WhoisErrorProps = {
error: Error & { digest?: string };
- reset: () => void;
+ unstable_retry: () => void;
};
-const WhoisError: FC<WhoisErrorProps> = ({ error }) => {
- useEffect(() => {
- console.error(error);
- }, [error]);
-
- return (
- <div className="mt-12 flex flex-col items-center gap-2">
- <h2>Something went wrong!</h2>
- <p className="mt-2 text-center text-sm text-zinc-500 dark:text-zinc-400">
- Digest: {error.digest}
- </p>
- </div>
- );
-};
+const WhoisError: FC<WhoisErrorProps> = ({ error, unstable_retry }) => (
+ <BoundaryError error={error} retry={unstable_retry} />
+);
export default WhoisError;
diff --git a/app/lookup/[domain]/whois/page.tsx b/app/lookup/[domain]/whois/page.tsx
index 3752e40..81949c0 100644
--- a/app/lookup/[domain]/whois/page.tsx
+++ b/app/lookup/[domain]/whois/page.tsx
@@ -3,6 +3,7 @@ import Link from 'next/link';
import { type FC, Fragment } from 'react';
import { recordLookupAfter } from '@/lib/search';
+import { UserFacingError } from '@/lib/user-facing-error';
import { getBaseDomain } from '@/lib/utils';
import { lookupWhois } from '@/lib/whois';
@@ -45,12 +46,16 @@ const WhoisResultsPage: FC<WhoisResultsPageProps> = async ({
const forceOriginal = force !== undefined;
const baseDomain = getBaseDomain(domain);
- const results = await lookupWhois(forceOriginal ? domain : baseDomain);
+ const lookupTarget = forceOriginal ? domain : baseDomain;
+ const results = await lookupWhois(lookupTarget);
await recordLookupAfter(domain, 'whois', results.length > 0);
if (results.length === 0) {
- throw new Error('No results found');
+ throw new UserFacingError({
+ title: 'No WHOIS results',
+ description: `No WHOIS data is available for ${lookupTarget}. The domain may be unregistered or the WHOIS server may not return data for this TLD.`,
+ });
}
return (
diff --git a/components/boundary-error.tsx b/components/boundary-error.tsx
new file mode 100644
index 0000000..d6caf01
--- /dev/null
+++ b/components/boundary-error.tsx
@@ -0,0 +1,64 @@
+'use client';
+
+import { type FC, useEffect, useState } from 'react';
+
+import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
+
+import { parseUserFacingDigest } from '@/lib/user-facing-error';
+
+type BoundaryErrorProps = {
+ error: Error & { digest?: string };
+ retry: () => void;
+ fallbackTitle?: string;
+};
+
+export const BoundaryError: FC<BoundaryErrorProps> = ({
+ error,
+ retry,
+ fallbackTitle = 'Something went wrong!',
+}) => {
+ const [isPending, setIsPending] = useState(false);
+
+ useEffect(() => {
+ console.error(error);
+ }, [error]);
+
+ const userFacing = parseUserFacingDigest(error.digest);
+ const title = userFacing?.title ?? fallbackTitle;
+ const description = userFacing?.description;
+ const retryable = userFacing ? (userFacing.retryable ?? false) : true;
+
+ const handleRetry = () => {
+ setIsPending(true);
+ retry();
+ };
+
+ return (
+ <div className="mt-12 flex flex-col items-center gap-2" role="alert">
+ <h2 className="text-xl font-bold">{title}</h2>
+ {description && (
+ <p className="mt-1 max-w-prose text-center text-sm leading-relaxed text-zinc-600 dark:text-zinc-300">
+ {description}
+ </p>
+ )}
+ {retryable && (
+ <Button
+ variant="outline"
+ className="mt-4 min-w-28"
+ onClick={handleRetry}
+ disabled={isPending}
+ aria-busy={isPending}
+ >
+ {isPending && <Spinner className="size-4" aria-hidden="true" />}
+ {isPending ? 'Retrying...' : 'Try again'}
+ </Button>
+ )}
+ {!userFacing && error.digest && (
+ <p className="mt-2 text-center font-mono text-xs text-zinc-500 dark:text-zinc-400">
+ Error Digest: <span className="select-all">{error.digest}</span>
+ </p>
+ )}
+ </div>
+ );
+};
diff --git a/lib/bigquery.ts b/lib/bigquery.ts
index b2c6792..74ef855 100644
--- a/lib/bigquery.ts
+++ b/lib/bigquery.ts
@@ -2,6 +2,8 @@ import { getAccessToken } from 'web-auth-library/google';
import { env } from '@/env';
+import { UserFacingError } from './user-facing-error';
+
const credentials = env.GOOGLE_SERVICE_KEY_B64
? (JSON.parse(
Buffer.from(env.GOOGLE_SERVICE_KEY_B64, 'base64').toString(),
@@ -46,8 +48,18 @@ export const insertRows = async ({
if (!response.ok) {
const errorBody = await response.text();
- throw new Error(
- `Failed to insert data into BigQuery: ${response.status} ${errorBody}`,
+ throw new UserFacingError(
+ {
+ title: 'BigQuery is unavailable',
+ description:
+ 'BigQuery returned an error and may be temporarily down. Please try again shortly.',
+ retryable: true,
+ },
+ {
+ cause: new Error(
+ `Failed to insert data into BigQuery: ${response.status} ${errorBody}`,
+ ),
+ },
);
}
};
@@ -98,8 +110,18 @@ export const query = async <T extends Record<string, any>>({
if (!response.ok) {
const errorBody = await response.text();
- throw new Error(
- `Failed to execute query in BigQuery: ${response.status} ${errorBody}`,
+ throw new UserFacingError(
+ {
+ title: 'BigQuery is unavailable',
+ description:
+ 'BigQuery returned an error and may be temporarily down. Please try again shortly.',
+ retryable: true,
+ },
+ {
+ cause: new Error(
+ `Failed to execute query in BigQuery: ${response.status} ${errorBody}`,
+ ),
+ },
);
}
diff --git a/lib/certs.ts b/lib/certs.ts
index d837460..04f3657 100644
--- a/lib/certs.ts
+++ b/lib/certs.ts
@@ -1,3 +1,5 @@
+import { UserFacingError } from './user-facing-error';
+
export type CertsData = {
issuer_ca_id: number;
issuer_name: string;
@@ -11,16 +13,41 @@ export type CertsData = {
}[];
export const lookupCerts = async (domain: string): Promise<CertsData> => {
- const response = await fetch(
- 'https://crt.sh?' +
- new URLSearchParams({
- Identity: domain,
- output: 'json',
- }),
- );
+ let response: Response;
+ try {
+ response = await fetch(
+ 'https://crt.sh?' +
+ new URLSearchParams({
+ Identity: domain,
+ output: 'json',
+ }),
+ );
+ } catch (error) {
+ throw new UserFacingError(
+ {
+ title: "Couldn't reach crt.sh",
+ description:
+ "We couldn't complete the request to crt.sh. Please try again shortly.",
+ retryable: true,
+ },
+ { cause: error },
+ );
+ }
if (!response.ok) {
- throw new Error('Failed to fetch certs');
+ throw new UserFacingError(
+ {
+ title: 'crt.sh is unavailable',
+ description:
+ 'crt.sh returned an error and may be temporarily down. Please try again shortly.',
+ retryable: true,
+ },
+ {
+ cause: new Error(
+ `crt.sh responded with HTTP ${response.status} ${response.statusText}`,
+ ),
+ },
+ );
}
const data: CertsData = await response.json();
diff --git a/lib/github.ts b/lib/github.ts
index 314f90f..f3b9db6 100644
--- a/lib/github.ts
+++ b/lib/github.ts
@@ -168,7 +168,6 @@ export const getStargazersSummary = async (
const result = await graphqlResponse.json();
if (result.errors) {
- console.error('GraphQL errors:', result.errors);
throw new Error(`GraphQL errors: ${JSON.stringify(result.errors)}`);
}
diff --git a/lib/ips.test.ts b/lib/ips.test.ts
index 5a0fdd9..715bac3 100644
--- a/lib/ips.test.ts
+++ b/lib/ips.test.ts
@@ -2,6 +2,7 @@ import isIP from 'validator/lib/isIP';
import { describe, expect, it, vi } from 'vitest';
import {
+ getIpDetails,
ipToDnsName,
ipv4ToDnsName,
ipv6ToDnsName,
@@ -35,6 +36,20 @@ describe('ipToDnsName', () => {
});
});
+describe('getIpDetails', () => {
+ it('should throw a user-facing error for invalid IP addresses', async () => {
+ await expect(getIpDetails('not-an-ip')).rejects.toThrow(
+ /Invalid IP address/,
+ );
+ await expect(getIpDetails('../../../etc/passwd')).rejects.toThrow(
+ /Invalid IP address/,
+ );
+ await expect(getIpDetails('999.999.999.999')).rejects.toThrow(
+ /Invalid IP address/,
+ );
+ });
+});
+
describe('lookupReverse', () => {
it('should return an array of domain names from reverse DNS lookups', async () => {
const fakeResponse = {
@@ -60,15 +75,14 @@ describe('lookupReverse', () => {
expect(results).toEqual([]);
});
- it('should throw an error when the API call for DNS lookup fails', async () => {
+ it('should throw a user-facing error when the API call for DNS lookup fails', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
+ status: 503,
statusText: 'Service Unavailable',
});
- await expect(lookupReverse('8.8.4.4')).rejects.toThrow(
- 'Error fetching DNS records: Service Unavailable',
- );
+ await expect(lookupReverse('8.8.4.4')).rejects.toThrow(/Cloudflare DNS/);
});
});
diff --git a/lib/ips.ts b/lib/ips.ts
index 092bbd0..747bee7 100644
--- a/lib/ips.ts
+++ b/lib/ips.ts
@@ -1,6 +1,8 @@
import DataLoader from 'dataloader';
import isIP from 'validator/lib/isIP';
+import { UserFacingError } from './user-facing-error';
+
type IpDetails = {
country: string;
countryCode: string;
@@ -18,13 +20,42 @@ type IpDetails = {
};
export const getIpDetails = async (ip: string) => {
- if (!isIP(ip)) throw new Error('Invalid IP address');
+ if (!isIP(ip))
+ throw new UserFacingError({
+ title: 'Invalid IP address',
+ description: 'The provided IP address is not valid.',
+ });
const url = new URL(`http://ip-api.com/json/${encodeURIComponent(ip)}`);
- const response = await fetch(url.toString());
+ let response: Response;
+ try {
+ response = await fetch(url.toString());
+ } catch (error) {
+ throw new UserFacingError(
+ {
+ title: "Couldn't reach ip-api.com",
+ description:
+ "We couldn't complete the request to ip-api.com. Please try again shortly.",
+ retryable: true,
+ },
+ { cause: error },
+ );
+ }
if (!response.ok)
- throw new Error(`Error fetching IP details: ${response.statusText}`);
+ throw new UserFacingError(
+ {
+ title: 'ip-api.com is unavailable',
+ description:
+ 'ip-api.com returned an error and may be temporarily down. Please try again shortly.',
+ retryable: true,
+ },
+ {
+ cause: new Error(
+ `ip-api.com responded with HTTP ${response.status} ${response.statusText}`,
+ ),
+ },
+ );
const data = (await response.json()) as Record<string, any>;
delete data.status;
@@ -60,17 +91,49 @@ export const ipToDnsName = (ip: string) =>
ip.includes(':') ? ipv6ToDnsName(ip) : ipv4ToDnsName(ip);
export const lookupReverse = async (ip: string): Promise<string[]> => {
+ if (!isIP(ip)) {
+ throw new UserFacingError({
+ title: 'Invalid IP address',
+ description: 'The provided IP address is not valid.',
+ });
+ }
+
const reverseDnsName = ipToDnsName(ip);
- const response = await fetch(
- `https://cloudflare-dns.com/dns-query?name=${reverseDnsName}&type=PTR`,
- {
- headers: { Accept: 'application/dns-json' },
- },
- );
+ let response: Response;
+ try {
+ response = await fetch(
+ `https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(reverseDnsName)}&type=PTR`,
+ {
+ headers: { Accept: 'application/dns-json' },
+ },
+ );
+ } catch (error) {
+ throw new UserFacingError(
+ {
+ title: "Couldn't reach Cloudflare DNS",
+ description:
+ "We couldn't complete the request to Cloudflare DNS. Please try again shortly.",
+ retryable: true,
+ },
+ { cause: error },
+ );
+ }
if (!response.ok)
- throw new Error(`Error fetching DNS records: ${response.statusText}`);
+ throw new UserFacingError(
+ {
+ title: 'Cloudflare DNS is unavailable',
+ description:
+ 'Cloudflare DNS returned an error and may be temporarily down. Please try again shortly.',
+ retryable: true,
+ },
+ {
+ cause: new Error(
+ `Cloudflare DNS responded with HTTP ${response.status} ${response.statusText}`,
+ ),
+ },
+ );
const data = await response.json();
diff --git a/lib/resolvers/authoritative.ts b/lib/resolvers/authoritative.ts
index b4ae383..bb27aaa 100644
--- a/lib/resolvers/authoritative.ts
+++ b/lib/resolvers/authoritative.ts
@@ -12,6 +12,7 @@ import dnsPacket, {
import { retry } from '@/lib/utils';
+import { UserFacingError } from '../user-facing-error';
import {
DnsResolver,
type RawRecord,
@@ -37,13 +38,38 @@ export class AuthoritativeResolver extends DnsResolver {
private static readonly MAX_RECURSION_DEPTH = 20;
private async getRootServers() {
- const response = await fetch('https://www.internic.net/domain/named.root', {
- next: {
- revalidate: 7 * 24 * 60 * 60,
- },
- });
+ let response: Response;
+ try {
+ response = await fetch('https://www.internic.net/domain/named.root', {
+ next: {
+ revalidate: 7 * 24 * 60 * 60,
+ },
+ });
+ } catch (error) {
+ throw new UserFacingError(
+ {
+ title: "Couldn't reach InterNIC root servers list",
+ description:
+ "We couldn't complete the request to the InterNIC root servers list. Please try again shortly.",
+ retryable: true,
+ },
+ { cause: error },
+ );
+ }
if (!response.ok) {
- throw new Error(`Failed to fetch root servers: HTTP ${response.status}`);
+ throw new UserFacingError(
+ {
+ title: 'InterNIC root servers list is unavailable',
+ description:
+ 'The InterNIC root servers list returned an error and may be temporarily down. Please try again shortly.',
+ retryable: true,
+ },
+ {
+ cause: new Error(
+ `Failed to fetch root servers: HTTP ${response.status}`,
+ ),
+ },
+ );
}
const body = await response.text();
@@ -51,7 +77,15 @@ export class AuthoritativeResolver extends DnsResolver {
const aRecords = body.match(/\sA\s+(.+)/g);
if (!aRecords) {
- throw new Error('Failed to fetch root servers');
+ throw new UserFacingError(
+ {
+ title: "Couldn't reach InterNIC root servers list",
+ description:
+ "We couldn't complete the request to the InterNIC root servers list. Please try again shortly.",
+ retryable: true,
+ },
+ { cause: new Error('Failed to parse root servers') },
+ );
}
const ipAddresses = aRecords?.map(
diff --git a/lib/resolvers/base-doh.test.ts b/lib/resolvers/base-doh.test.ts
index 08f840c..13c0874 100644
--- a/lib/resolvers/base-doh.test.ts
+++ b/lib/resolvers/base-doh.test.ts
@@ -67,9 +67,10 @@ describe('BaseDoHResolver', () => {
});
});
- it('should throw an error for bad HTTP responses', async () => {
+ it('should throw a user-facing error for bad HTTP responses', async () => {
mockSendRequest.mockResolvedValue({
ok: false,
+ status: 500,
statusText: 'Internal Server Error',
url: 'https://dns.google/resolve',
});
@@ -78,8 +79,6 @@ describe('BaseDoHResolver', () => {
await expect(
resolver.resolveRecordType('example.com', 'A'),
- ).rejects.toThrow(
- 'Bad response from DoH Resolver: Internal Server Error from https://dns.google/resolve',
- );
+ ).rejects.toThrow(/DNS resolver/);
});
});
diff --git a/lib/resolvers/base-doh.ts b/lib/resolvers/base-doh.ts
index db604bd..9697a7e 100644
--- a/lib/resolvers/base-doh.ts
+++ b/lib/resolvers/base-doh.ts
@@ -1,4 +1,5 @@
import { RECORD_TYPES_BY_DECIMAL } from '../data';
+import { UserFacingError } from '../user-facing-error';
import { DnsResolver, type RecordType, type ResolverResponse } from './base';
type DoHResponse = {
@@ -41,10 +42,22 @@ export abstract class BaseDoHResolver extends DnsResolver {
type: RecordType,
): Promise<ResolverResponse> {
const response = await this.sendRequest(domain, type);
- if (!response.ok)
- throw new Error(
- `Bad response from DoH Resolver: ${response.statusText} from ${response.url}`,
+ if (!response.ok) {
+ const retryable = response.status === 429 || response.status >= 500;
+ throw new UserFacingError(
+ {
+ title: 'DNS resolver is unavailable',
+ description:
+ 'The DNS resolver returned an error and may be temporarily down. Please try again shortly.',
+ retryable,
+ },
+ {
+ cause: new Error(
+ `Bad response from DoH Resolver: HTTP ${response.status} ${response.statusText} from ${response.url}`,
+ ),
+ },
);
+ }
const results = (await response.json()) as DoHResponse;
if (!results.Answer) {
diff --git a/lib/resolvers/internal.test.ts b/lib/resolvers/internal.test.ts
index e8ba01e..777c38f 100644
--- a/lib/resolvers/internal.test.ts
+++ b/lib/resolvers/internal.test.ts
@@ -56,9 +56,7 @@ describe('InternalDoHResolver', () => {
await expect(
resolver.resolveRecordType('example.com', 'A'),
- ).rejects.toThrow(
- 'Failed to fetch results for lhr from https://example.com/api/internal/resolve/lhr?resolver=alibaba&type=A&domain=example.com: 500 Internal Server Error',
- );
+ ).rejects.toThrow(/DNS resolver \(lhr\)/);
});
it('should handle multiple DNS record types', async () => {
diff --git a/lib/resolvers/internal.ts b/lib/resolvers/internal.ts
index 02cda5b..374ce1b 100644
--- a/lib/resolvers/internal.ts
+++ b/lib/resolvers/internal.ts
@@ -1,5 +1,6 @@
import { env } from '@/env';
+import { UserFacingError } from '../user-facing-error';
import {
DnsResolver,
type RecordType,
@@ -47,10 +48,20 @@ export class InternalDoHResolver extends DnsResolver {
url.searchParams.set('domain', domain);
const response = await fetch(url, this.requestInit);
- if (!response.ok)
- throw new Error(
- `Failed to fetch results for ${this.location} from ${url}: ${response.status} ${response.statusText}`,
+ if (!response.ok) {
+ throw new UserFacingError(
+ {
+ title: `DNS resolver (${this.location}) is unavailable`,
+ description: `The DNS resolver for ${this.location} returned an error and may be temporarily down. Please try again shortly.`,
+ retryable: true,
+ },
+ {
+ cause: new Error(
+ `Failed to fetch results for ${this.location} from ${url}: ${response.status} ${response.statusText}`,
+ ),
+ },
);
+ }
const results = (await response.json()) as ResolverMultiResponse;
@@ -67,10 +78,20 @@ export class InternalDoHResolver extends DnsResolver {
url.searchParams.set('domain', domain);
const response = await fetch(url, this.requestInit);
- if (!response.ok)
- throw new Error(
- `Failed to fetch results for ${this.location} from ${url}: ${response.status} ${response.statusText}`,
+ if (!response.ok) {
+ throw new UserFacingError(
+ {
+ title: `DNS resolver (${this.location}) is unavailable`,
+ description: `The DNS resolver for ${this.location} returned an error and may be temporarily down. Please try again shortly.`,
+ retryable: true,
+ },
+ {
+ cause: new Error(
+ `Failed to fetch results for ${this.location} from ${url}: ${response.status} ${response.statusText}`,
+ ),
+ },
);
+ }
const results = (await response.json()) as ResolverMultiResponse;
diff --git a/lib/user-facing-error.ts b/lib/user-facing-error.ts
new file mode 100644
index 0000000..cd456a0
--- /dev/null
+++ b/lib/user-facing-error.ts
@@ -0,0 +1,47 @@
+// Next.js redacts `error.message` for server-thrown errors in production but
+// forwards `error.digest` verbatim (this is how internal sentinels like
+// NEXT_REDIRECT and NEXT_HTTP_ERROR_FALLBACK;404 reach the client). We piggy-
+// back on that channel: the constructor sets a custom digest containing the
+// JSON payload, and `error.tsx` boundaries decode it back.
+
+const SENTINEL = '__USER_FACING_ERROR__:';
+
+export type UserFacingErrorPayload = {
+ title: string;
+ description: string;
+ retryable?: boolean;
+};
+
+export class UserFacingError extends Error {
+ public readonly digest: string;
+
+ constructor(
+ public readonly payload: UserFacingErrorPayload,
+ options?: ErrorOptions,
+ ) {
+ super(payload.title, options);
+ this.name = 'UserFacingError';
+ this.digest = SENTINEL + JSON.stringify(payload);
+ }
+}
+
+export const parseUserFacingDigest = (
+ digest: string | undefined,
+): UserFacingErrorPayload | null => {
+ if (!digest || !digest.startsWith(SENTINEL)) return null;
+ try {
+ const parsed = JSON.parse(digest.slice(SENTINEL.length));
+ if (
+ parsed &&
+ typeof parsed === 'object' &&
+ typeof parsed.title === 'string' &&
+ typeof parsed.description === 'string' &&
+ (parsed.retryable === undefined || typeof parsed.retryable === 'boolean')
+ ) {
+ return parsed as UserFacingErrorPayload;
+ }
+ } catch {
+ // fall through
+ }
+ return null;
+};
diff --git a/lib/whois.ts b/lib/whois.ts
index 62c4a21..863e932 100644
--- a/lib/whois.ts
+++ b/lib/whois.ts
@@ -1,5 +1,6 @@
import { firstResult as getFirstResult, whoisDomain } from 'whoiser';
+import { UserFacingError } from './user-facing-error';
import { getBaseDomain, isValidDomain } from './utils';
export const formatDate = (date: Date) => date.toISOString().split('T')[0];
@@ -11,10 +12,23 @@ const parseDateSafe = (date: string): Date | null => {
};
export const lookupWhois = async (domain: string) => {
- const result = await whoisDomain(domain, {
- raw: true,
- timeout: 5000,
- });
+ let result: Awaited<ReturnType<typeof whoisDomain>>;
+ try {
+ result = await whoisDomain(domain, {
+ raw: true,
+ timeout: 5000,
+ });
+ } catch (error) {
+ throw new UserFacingError(
+ {
+ title: 'WHOIS lookup failed',
+ description:
+ "We couldn't reach the WHOIS server for this domain. It may be temporarily unavailable or rate limiting our requests. Please try again shortly.",
+ retryable: true,
+ },
+ { cause: error },
+ );
+ }
const mappedResults: Record<string, string> = {};
for (const key in result) {
@@ -116,8 +130,7 @@ export const getWhoisSummary = async (
createdAt: createdAt && formatDate(createdAt),
dnssec: firstResult['DNSSEC']?.toString() || null,
};
- } catch (error) {
- console.error(error);
+ } catch {
return {
registered: true,
registrar: null,