Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add error serializer for SSR/Browser hydration #33

Merged
merged 48 commits into from
Sep 21, 2022
Merged

Conversation

belgattitude
Copy link
Owner

@belgattitude belgattitude commented Sep 13, 2022

Serializer

HttpException can be serialized to json and vice-versa. It can be useful in ssr frameworks such as
nextjs whenever a server error should be shared within the browser context (see also
the excellent superjson).

Serialization supports the 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
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

@belgattitude belgattitude self-assigned this Sep 21, 2022
@belgattitude belgattitude added the enhancement New feature or request label Sep 21, 2022
@belgattitude belgattitude merged commit 9dce653 into main Sep 21, 2022
@belgattitude belgattitude deleted the error-serializer branch September 21, 2022 18:04
@belgattitude belgattitude mentioned this pull request Sep 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant