Skip to content

Instantly share code, notes, and snippets.

@baronTommy
Last active June 15, 2020 06:43
Show Gist options
  • Save baronTommy/919dbc40bf265b363b6490540a9436e4 to your computer and use it in GitHub Desktop.
Save baronTommy/919dbc40bf265b363b6490540a9436e4 to your computer and use it in GitHub Desktop.
TypeScriptエラーハンドリング
type Profile = {
id: number;
name: string;
foo: string;
bar: string;
};
const fetchProfile = () => {
return fetch("/profile").then<Profile>((res) => res.json());
};
const main = async () => {
let profile: Profile | undefined;
try {
profile = await fetchProfile();
} catch (e) {
// エラーハンドリング
}
if (profile) {
console.log(profile.name, "さん");
}
};
type Profile = {
id: number;
name: string;
foo: string;
bar: string;
};
abstract class Data<T> {
protected constructor(private _value: T) {}
get value(): T {
return { ...this._value } as const;
}
}
class SuccessData<T> extends Data<T> {
static of<V>(v: V): SuccessData<V> {
return new SuccessData(v);
}
}
class ExceptionData<T> extends Data<T> {
static of<V>(v: V): ExceptionData<V> {
return new ExceptionData(v);
}
}
const fetchProfile = () => {
return fetch("/profile")
.then<Profile>((res) => res.json())
.then((res) => SuccessData.of(res))
.catch((e) => ExceptionData.of(e));
};
const main = async () => {
const res = await fetchProfile().catch<never>((e) => e);
if (res instanceof SuccessData) {
const profile = res.value;
console.log(profile.name, "さん");
return;
}
if (res instanceof ExceptionData) {
// エラーハンドリング
return;
}
throw new Error("想定外");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment