Errors, Exceptions and WP_Error

Handle failures so the site keeps working and the log tells you why: exceptions and WP_Error, each in its place.

WordPress returns WP_Error. Modern PHP throws exceptions. Your plugin needs both. An uncaught exception from a library takes the whole page down, and a WP_Error nobody checks turns into a silent bug. This module draws the line between them.

CoursePHP for WordPress Developers · Module 6 of 9 · Stage 2 "Architecture"
LearnThrowable, custom exceptions, WP_Error in core and REST, recovery mode and logging
HowShort lessons with code from real plugins, Terminal practice in the browser, interview questions after every lesson

The idea in one picture

flowchart LR
  L["Library throws<br/>Exception"] --> C["try / catch<br/>at the boundary"]
  C --> W["WP_Error<br/>for WordPress APIs"]
  W --> R["REST response<br/>status + message"]
  C --> G["error_log<br/>the cause"]
  classDef step fill:#f5f3ff,stroke:#777BB4,color:#1e1b4b
  classDef key fill:#777BB4,stroke:#4f5b93,color:#ffffff

Exceptions stay inside your code, WP_Error crosses into WordPress.

Before → after

BeforeAfter Module 6
A white screen from an uncaught exceptiontry/catch at the plugin boundary
WP_Error returned and never checkedis_wp_error() on every call that can fail
die() in plugin codeErrors returned or logged
"Something went wrong"A log entry with the cause

You'll be able to answer

  • How does Exception differ from Error in PHP?
  • When do you return WP_Error and when do you throw?
  • What is WordPress recovery mode?