Skip to content

Commit

Permalink
Merge pull request #33 from belgattitude/error-serializer
Browse files Browse the repository at this point in the history
Add error serializer for SSR/Browser hydration
  • Loading branch information
belgattitude authored Sep 21, 2022
2 parents 59bce23 + 415e2b3 commit 9dce653
Show file tree
Hide file tree
Showing 90 changed files with 6,843 additions and 180 deletions.
43 changes: 43 additions & 0 deletions .changeset/friendly-ducks-fry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
'@belgattitude/http-exception': minor
---

Add HttpException json serializer.

Two new methods `fromJson` and `toJson` exported from `@belgattitude/http-exception/serializer`.



HttpException can be serialized to json and vice-versa. It can be useful in ssr frameworks such as
[nextjs](https://nextjs.org/) whenever a server error should be shared within the browser context (see also
the excellent [superjson](https://github.com/blitz-js/superjson#recipes)).

Serialization supports the [Error.cause](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause)
but totally ignores it the runtime (node or browser) does not support it (or without polyfills).

Additionally, you can pass any native errors (`Error`, `EvalError`, `RangeError`, `ReferenceError`, `SyntaxError`, `TypeError`, `URIError`)
as well as a custom one (the later will be transformed to the base type Error). That was necessary to support the cause param.


| Method |
|-----------------------------------------------------------------------|
| **toJson**(HttpException | NativeError | Error): string |
| **fromJson**(string): HttpException | NativeError | Error |

```typescript
import { HttpForbidden, HttpUnavailableForLegalReasons } from "@belgattitude/http-exception";
import { fromJson, toJson } from '@belgattitude/http-exception/serializer';

const e = new HttpForbidden({
url: 'https://www.cool.me'
/*
cause: new HttpUnavailableForLegalReasons({
cause: new Error('example with cause')
}),
*/
})

const json = toJson(e);
const exception = fromJson(json); // e === exception
```

41 changes: 38 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,43 @@ const false2 = new HttpInternalServerError() instanceof HttpClientException;
const false3 = new Error() instanceof HttpException;
```

### Serializer

HttpException can be serialized to json and vice-versa. It can be useful in ssr frameworks such as
[nextjs](https://nextjs.org/) whenever a server error should be shared within the browser context (see also
the excellent [superjson](https://github.com/blitz-js/superjson#recipes)).

Serialization supports the [Error.cause](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause)
but totally ignores it the runtime (node or browser) does not support it (or without polyfills).

Additionally, you can pass any native errors (`Error`, `EvalError`, `RangeError`, `ReferenceError`, `SyntaxError`, `TypeError`, `URIError`)
as well as a custom one (the later will be transformed to the base type Error). That was necessary to support the cause param.

| Method |
| ------------------------------------------------------------------- |
| **toJson**(HttpException | NativeError | Error): string |
| **fromJson**(string): HttpException | NativeError | Error |

```typescript
import {
HttpForbidden,
HttpUnavailableForLegalReasons,
} from "@belgattitude/http-exception";
import { fromJson, toJson } from "@belgattitude/http-exception/serializer";

const e = new HttpForbidden({
url: "https://www.cool.me",
/*
cause: new HttpUnavailableForLegalReasons({
cause: new Error('example with cause')
}),
*/
});

const json = toJson(e);
const exception = fromJson(json); // e === exception
```

### List

| Status | Class | Typeguard | Docs |
Expand Down Expand Up @@ -162,8 +199,6 @@ const false3 = new Error() instanceof HttpException;
| 510 | **↳↳ HttpNotExtended** | | |
| 511 | **↳↳ HttpNetwordAuthenticationRequired** | | |


## Links

[![Featured on Openbase](https://badges.openbase.com/js/featured/@belgattitude/http-exception.svg?token=fn2tsbLKVEbqoZyORlQmPQ637fEcf40bTPdm8q2q3z8=)](https://openbase.com/js/@belgattitude/http-exception?utm_source=embedded&utm_medium=badge&utm_campaign=rate-badge)

[![Featured on Openbase](https://badges.openbase.com/js/featured/@belgattitude/http-exception.svg?token=fn2tsbLKVEbqoZyORlQmPQ637fEcf40bTPdm8q2q3z8=)](https://openbase.com/js/@belgattitude/http-exception?utm_source=embedded&utm_medium=badge&utm_campaign=rate-badge)
2 changes: 1 addition & 1 deletion examples/nextjs-app/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const {
module.exports = {
root: true,
parserOptions: {
project: './tsconfig.json',
project: __dirname + '/tsconfig.json',
},
ignorePatterns: [...getDefaultIgnorePatterns()],
extends: [
Expand Down
38 changes: 12 additions & 26 deletions examples/nextjs-app/README.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,20 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
# Nextjs example

## Getting Started
## Development

First, run the development server:
> Will use tsconfig path aliases, changes in @belgattitude/http-exception packages
> are immediately reflected
```bash
npm run dev
# or
```
yarn dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file.

[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`.

The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.

## Learn More

To learn more about Next.js, take a look at the following resources:
## Build

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
> Won't use tsconfig path aliases and thus requires a build of @belgattitude/http-exception packages.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
```
yarn g:build-packages
yarn build
yarn start
```
45 changes: 45 additions & 0 deletions examples/nextjs-app/components/Scenarios.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { HttpBadGateway, HttpForbidden } from '@belgattitude/http-exception';
import { toJson, fromJson } from '@belgattitude/http-exception/serializer';
import type { FC } from 'react';
import superjson from 'superjson';

const SimpleSerialize: FC = () => {
const cause = new HttpForbidden();
const err = new HttpBadGateway({
url: 'http://localhost:3000',
cause,
});
const converted = fromJson(toJson(err));
return (
<div>
<div>SimpleSerialize</div>
<div>{JSON.stringify(converted)}</div>
</div>
);
};

export const SuperJsonSerialize: FC = () => {
const cause = new HttpForbidden();
const err = new HttpBadGateway({
url: 'http://localhost:3000',
cause,
});
const stringified = superjson.stringify(err);
const converted = superjson.parse(stringified);

return (
<div className={'rounded-xl p-8 border-2'}>
<div>Superjson</div>
<div>{JSON.stringify(converted)}</div>
</div>
);
};

export const Scenarios = () => {
return (
<div>
<SimpleSerialize />
<SuperJsonSerialize />
</div>
);
};
6 changes: 5 additions & 1 deletion examples/nextjs-app/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@ const NEXTJS_IGNORE_TYPECHECK = trueEnv.includes(
process.env?.NEXTJS_IGNORE_TYPECHECK ?? 'false'
);

const TYPESCRIPT_CONFIG = process.env.TSCONFIG
? process.env.TSCONFIG
: './tsconfig.json';

/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
productionBrowserSourceMaps: true,
swcMinify: true,
typescript: {
tsconfigPath: './tsconfig.json',
tsconfigPath: TYPESCRIPT_CONFIG,
ignoreBuildErrors: NEXTJS_IGNORE_TYPECHECK,
},
eslint: {
Expand Down
10 changes: 8 additions & 2 deletions examples/nextjs-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,30 @@
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"build": "cross-env TSCONFIG=./tsconfig.no-paths.json next build",
"start": "next start",
"clean": "rimraf --no-glob ./.next ./coverage ./tsconfig.tsbuildinfo",
"typecheck": "tsc --project tsconfig.json --noEmit",
"typecheck-no-paths": "tsc --project tsconfig.no-paths.json --noEmit",
"lint": "eslint . --ext .ts,.tsx,.js,.jsx,.mjs,.cjs,.mts,.cts --cache --cache-location ../../.cache/eslint/nextjs-esm.eslintcache",
"prettier-check": "yarn run --top-level prettier --check --config ../../.prettierrc.js --ignore-path ../../.prettierignore \"./**/*.{js,jsx,cjs,mjs,ts,tsx,mts,md,mdx,json,css,scss,less}\"",
"prettier-fix": "yarn run --top-level prettier --write --config ../../.prettierrc.js --ignore-path ../../.prettierignore \"./**/*.{js,jsx,cjs,mjs,ts,tsx,mts,md,mdx,json,css,scss,less}\"",
"fix-staged": "lint-staged --allow-empty"
},
"dependencies": {
"@belgattitude/http-exception": "workspace:^",
"next": "12.3.1",
"react": "18.2.0",
"react-dom": "18.2.0"
"react-dom": "18.2.0",
"superjson": "1.10.0",
"tailwindcss": "3.1.8"
},
"devDependencies": {
"@belgattitude/eslint-config-bases": "1.9.0",
"@types/node": "18.7.18",
"@types/react": "18.0.20",
"@types/react-dom": "18.0.6",
"cross-env": "7.0.3",
"eslint": "8.23.1",
"eslint-config-next": "12.3.1",
"rimraf": "3.0.2",
Expand Down
70 changes: 70 additions & 0 deletions examples/nextjs-app/pages/getServerSideProps.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import type { HttpException } from '@belgattitude/http-exception';
import { HttpNotFound, HttpRequestTimeout } from '@belgattitude/http-exception';
import { fromJson, toJson } from '@belgattitude/http-exception/serializer';
import type { GetServerSideProps, InferGetServerSidePropsType } from 'next';
import { Scenarios } from '../components/Scenarios';

type ApiData =
| {
success: true;
data: {
id: string;
};
}
| {
success: false;
error: string;
};

type Props = {
apiData: ApiData;
};

export default function MonitorSentrySsrRoute(
props: InferGetServerSidePropsType<typeof getServerSideProps>
) {
const { apiData } = props;
const error: Error | null = apiData.success ? null : fromJson(apiData.error);
console.log('apiData', apiData);
return (
<div>
<h1>Should display the error below</h1>
<pre>{JSON.stringify(error, null, 2)}</pre>
<div>{JSON.stringify(apiData)}</div>
<Scenarios />
</div>
);
}

const fetchApiDataAlwaysRequestTimeout = async (): Promise<
Props['apiData']
> => {
throw new HttpRequestTimeout({
message: 'Fake request timeout',
url: 'http://localhost:3001',
});
};

export const getServerSideProps: GetServerSideProps<Props> = async (
_context
) => {
let apiData: ApiData;
try {
apiData = await fetchApiDataAlwaysRequestTimeout();
} catch (e) {
if (e instanceof HttpNotFound) {
return {
notFound: true,
};
}
apiData = {
success: false,
error: toJson(e as HttpException),
};
}
return {
props: {
apiData,
},
};
};
5 changes: 5 additions & 0 deletions examples/nextjs-app/postcss.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
plugins: {
tailwindcss: {},
},
};
29 changes: 3 additions & 26 deletions examples/nextjs-app/styles/globals.css
Original file line number Diff line number Diff line change
@@ -1,26 +1,3 @@
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}

a {
color: inherit;
text-decoration: none;
}

* {
box-sizing: border-box;
}

@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
body {
color: white;
background: black;
}
}
@tailwind base;
@tailwind components;
@tailwind utilities;
6 changes: 6 additions & 0 deletions examples/nextjs-app/tailwind.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{js,ts,jsx,tsx}'],
theme: {},
plugins: [],
};
10 changes: 9 additions & 1 deletion examples/nextjs-app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,15 @@
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
"incremental": true,
"paths": {
"@belgattitude/http-exception": [
"../../packages/http-exception/src/index"
],
"@belgattitude/http-exception/serializer": [
"../../packages/http-exception/src/serializer/index"
]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
Expand Down
7 changes: 7 additions & 0 deletions examples/nextjs-app/tsconfig.no-paths.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "./tsconfig.json",
"compilerOptions": {
"paths": {}
}
}
Loading

0 comments on commit 9dce653

Please sign in to comment.