惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
AI
AI
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
H
Hacker News: Front Page
P
Proofpoint News Feed
Know Your Adversary
Know Your Adversary
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Hacker News
The Hacker News
腾讯CDC
O
OpenAI News
Vercel News
Vercel News
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
量子位
S
Schneier on Security
T
Tor Project blog
B
Blog
The Register - Security
The Register - Security
宝玉的分享
宝玉的分享
S
Securelist
有赞技术团队
有赞技术团队
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
G
GRAHAM CLULEY
Hugging Face - Blog
Hugging Face - Blog
W
WeLiveSecurity
D
DataBreaches.Net
TaoSecurity Blog
TaoSecurity Blog
博客园 - Franky
Latest news
Latest news
I
Intezer
Hacker News: Ask HN
Hacker News: Ask HN
WordPress大学
WordPress大学
PCI Perspectives
PCI Perspectives
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
小众软件
小众软件
GbyAI
GbyAI
F
Full Disclosure
V
V2EX
Project Zero
Project Zero
The Last Watchdog
The Last Watchdog
T
Tenable Blog
Security Latest
Security Latest
Attack and Defense Labs
Attack and Defense Labs
F
Fortinet All Blogs
S
Secure Thoughts
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google DeepMind News
Google DeepMind News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Get a catch block error message with TypeScript
2021-10-28 · via Kent C. Dodds Blog

Alrighty, let's talk about this:

const reportError = ({ message }) => {
	// send the error to our logging service...
}

try {
	throw new Error('Oh no!')
} catch (error) {
	// we'll proceed, but let's report it
	reportError({ message: error.message })
}

Good so far? Well, that's because this is JavaScript. Let's throw TypeScript at this:

const reportError = ({ message }: { message: string }) => {
	// send the error to our logging service...
}

try {
	throw new Error('Oh no!')
} catch (error) {
	// we'll proceed, but let's report it
	reportError({ message: error.message })
}

That reportError call there isn't happy. Specifically it's the error.message bit. It's because (as of recently) TypeScript defaults our error type to unknown. Which is truly what it is! In the world of errors, there's not much guarantees you can offer about the types of errors that are thrown. In fact, this is the same reason you can't provide the type for the .catch(error => {}) of a promise rejection with the promise generic (Promise<ResolvedValue, NopeYouCantProvideARejectedValueType>). In fact, it might not even be an error that's thrown at all. It could be just about anything:

throw 'What the!?'
throw 7
throw { wut: 'is this' }
throw null
throw new Promise(() => {})
throw undefined

Seriously, you can throw anything of any type. So that's easy right? We could just add a type annotation for the error to say this code will only throw an error right?

try {
	throw new Error('Oh no!')
} catch (error: Error) {
	// we'll proceed, but let's report it
	reportError({ message: error.message })
}

Not so fast! With that you'll get the following TypeScript compilation error:

Catch clause variable type annotation must be 'any' or 'unknown' if specified. ts(1196)

The reason for this is because even though in our code it looks like there's no way anything else could be thrown, JavaScript is kinda funny and so its perfectly possible for a third party library to do something funky like monkey-patching the error constructor to throw something different:

Error = function () {
	throw 'Flowers'
} as any

So what's a dev to do? The very best they can! So how about this:

try {
	throw new Error('Oh no!')
} catch (error) {
	let message = 'Unknown Error'
	if (error instanceof Error) message = error.message
	// we'll proceed, but let's report it
	reportError({ message })
}

There we go! Now TypeScript isn't yelling at us and more importantly we're handling the cases where it really could be something completely unexpected. Maybe we could do even better though:

try {
	throw new Error('Oh no!')
} catch (error) {
	let message
	if (error instanceof Error) message = error.message
	else message = String(error)
	// we'll proceed, but let's report it
	reportError({ message })
}

So here if the error isn't an actual Error object, then we'll just stringify the error and hopefully that will end up being something useful.

Then we can turn this into a utility for use in all our catch blocks:

function getErrorMessage(error: unknown) {
	if (error instanceof Error) return error.message
	return String(error)
}

const reportError = ({ message }: { message: string }) => {
	// send the error to our logging service...
}

try {
	throw new Error('Oh no!')
} catch (error) {
	// we'll proceed, but let's report it
	reportError({ message: getErrorMessage(error) })
}

This has been helpful for me in my projects. Hopefully it helps you as well.

Update: Nicolas had a nice suggestion for handling situations where the error object you're dealing with isn't an actual error. And then Jesse had a suggestion to stringify the error object if possible. So all together the combined suggestions looks like this:

type ErrorWithMessage = {
	message: string
}

function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
	return (
		typeof error === 'object' &&
		error !== null &&
		'message' in error &&
		typeof (error as Record<string, unknown>).message === 'string'
	)
}

function toErrorWithMessage(maybeError: unknown): ErrorWithMessage {
	if (isErrorWithMessage(maybeError)) return maybeError

	try {
		return new Error(JSON.stringify(maybeError))
	} catch {
		// fallback in case there's an error stringifying the maybeError
		// like with circular references for example.
		return new Error(String(maybeError))
	}
}

function getErrorMessage(error: unknown) {
	return toErrorWithMessage(error).message
}

Handy!

Conclusion

I think the key takeaway here is to remember that while TypeScript has its funny bits, don't dismiss a compilation error or warning from TypeScript just because you think it's impossible or whatever. Most of the time it absolutely is possible for the unexpected to happen and TypeScript does a pretty good job of forcing you to handle those unlikely cases... And you'll probably find they're not as unlikely as you think.