ext_php_rs/exception.rs
1//! Types and functions used for throwing exceptions from Rust to PHP.
2
3use std::{fmt::Debug, ptr};
4
5use crate::{
6 class::RegisteredClass,
7 error::{Error, Result},
8 ffi::zend_throw_exception,
9 ffi::zend_throw_exception_object,
10 flags::ClassFlags,
11 types::{ZendStr, Zval},
12 zend::{ClassEntry, ExecutorGlobals, ce},
13};
14
15/// Result type with the error variant as a [`PhpException`].
16pub type PhpResult<T = ()> = std::result::Result<T, PhpException>;
17
18/// Represents a PHP exception which can be thrown using the `throw()` function.
19/// Primarily used to return from a [`Result<T, PhpException>`] which can
20/// immediately be thrown by the `ext-php-rs` macro API.
21///
22/// [`From`] is implemented for [`String`], [`&str`], [`crate::error::Error`]
23/// and, behind the `anyhow` feature, `anyhow::Error`. Implement [`From<T>`]
24/// for your own error type to return it from these functions.
25#[derive(Debug)]
26pub struct PhpException {
27 message: String,
28 code: i32,
29 ex: &'static ClassEntry,
30 object: Option<Zval>,
31}
32
33impl PhpException {
34 /// Creates a new exception instance.
35 ///
36 /// # Parameters
37 ///
38 /// * `message` - Message to contain in the exception.
39 /// * `code` - Integer code to go inside the exception.
40 /// * `ex` - Exception type to throw.
41 #[must_use]
42 pub fn new(message: String, code: i32, ex: &'static ClassEntry) -> Self {
43 Self {
44 message,
45 code,
46 ex,
47 object: None,
48 }
49 }
50
51 /// Creates a new exception instance from a message, using the default PHP
52 /// `Exception` type as the exception type, with an integer code of
53 /// zero.
54 ///
55 /// # Parameters
56 ///
57 /// * `message` - Message to contain in the exception.
58 #[must_use]
59 pub fn from_message(message: String) -> Self {
60 Self::new(message, 0, ce::exception())
61 }
62
63 /// Creates an instance of an exception from a PHP class type and a message.
64 ///
65 /// # Parameters
66 ///
67 /// * `message` - Message to contain in the exception.
68 #[must_use]
69 pub fn from_class<T: RegisteredClass>(message: String) -> Self {
70 Self::new(message, 0, T::get_metadata().ce())
71 }
72
73 /// Set the Zval object for the exception.
74 ///
75 /// Exceptions can be based of instantiated Zval objects when you are
76 /// throwing a custom exception with stateful properties.
77 ///
78 /// # Parameters
79 ///
80 /// * `object` - The Zval object.
81 pub fn set_object(&mut self, object: Option<Zval>) {
82 self.object = object;
83 }
84
85 /// Builder function that sets the Zval object for the exception.
86 ///
87 /// Exceptions can be based of instantiated Zval objects when you are
88 /// throwing a custom exception with stateful properties.
89 ///
90 /// # Parameters
91 ///
92 /// * `object` - The Zval object.
93 #[must_use]
94 pub fn with_object(mut self, object: Zval) -> Self {
95 self.object = Some(object);
96 self
97 }
98
99 /// Throws the exception. Always leaves an exception pending in the engine.
100 ///
101 /// Does nothing if an exception is already pending: the engine propagates
102 /// that one, and throwing over it would discard its class and stack trace.
103 ///
104 /// When the exception itself cannot be thrown (an interface or abstract
105 /// class, a message containing a NUL byte, or an attached value that is not
106 /// an object) a plain `Error` is thrown instead. Its message names the
107 /// cause and carries the original message, so the failure is reported to
108 /// PHP rather than to the Rust caller, which sits inside an `extern "C"`
109 /// frame with no way to propagate it.
110 pub fn throw(self) {
111 if ExecutorGlobals::has_exception() {
112 return;
113 }
114
115 // The engine can bail out of every call below, and a bailout skips this
116 // frame's destructors. So the Rust strings are copied to the Zend heap and
117 // dropped first. The Zend allocator frees its copies at request shutdown.
118 let Self {
119 message,
120 code,
121 ex,
122 object,
123 } = self;
124 let zend_message = ZendStr::new(&message, false);
125 drop(message);
126
127 let result = match object {
128 Some(object) => throw_object(object),
129 None => throw_zend_str(ex, code, &zend_message),
130 };
131
132 if let Err(err) = result {
133 let class = ex.name().unwrap_or_default();
134 let message = String::from_utf8_lossy(zend_message.as_bytes()).replace('\0', "\\0");
135 let fallback = format!("cannot throw {class}: {err}; original message: {message}");
136 drop(message);
137 let zend_fallback = ZendStr::new(&fallback, false);
138 drop(fallback);
139 let _ = throw_zend_str(ce::error(), 0, &zend_fallback);
140 }
141 }
142}
143
144impl From<String> for PhpException {
145 fn from(str: String) -> Self {
146 Self::from_message(str)
147 }
148}
149
150impl From<&str> for PhpException {
151 fn from(str: &str) -> Self {
152 Self::from_message(str.into())
153 }
154}
155
156#[cfg(feature = "anyhow")]
157impl From<anyhow::Error> for PhpException {
158 fn from(err: anyhow::Error) -> Self {
159 Self::new(format!("{err:#}"), 0, crate::zend::ce::exception())
160 }
161}
162
163/// Throws an exception with a given message. See [`ClassEntry`] for some
164/// built-in exception types.
165///
166/// Returns a result containing nothing if the exception was successfully
167/// thrown.
168///
169/// # Parameters
170///
171/// * `ex` - The exception type to throw.
172/// * `message` - The message to display when throwing the exception.
173///
174/// # Errors
175///
176/// * [`Error::InvalidException`] - If the exception type is an interface or
177/// abstract class.
178/// * If the message contains NUL bytes.
179///
180/// # Examples
181///
182/// ```no_run
183/// use ext_php_rs::{zend::{ce, ClassEntry}, exception::throw};
184///
185/// throw(ce::compile_error(), "This is a CompileError.");
186/// ```
187pub fn throw(ex: &ClassEntry, message: &str) -> Result<()> {
188 throw_with_code(ex, 0, message)
189}
190
191/// Throws an exception with a given message and status code. See [`ClassEntry`]
192/// for some built-in exception types.
193///
194/// Returns a result containing nothing if the exception was successfully
195/// thrown.
196///
197/// # Parameters
198///
199/// * `ex` - The exception type to throw.
200/// * `code` - The status code to use when throwing the exception.
201/// * `message` - The message to display when throwing the exception.
202///
203/// # Errors
204///
205/// * [`Error::InvalidException`] - If the exception type is an interface or
206/// abstract class.
207/// * If the message contains NUL bytes.
208///
209/// # Examples
210///
211/// ```no_run
212/// use ext_php_rs::{zend::{ce, ClassEntry}, exception::throw_with_code};
213///
214/// throw_with_code(ce::compile_error(), 123, "This is a CompileError.");
215/// ```
216pub fn throw_with_code(ex: &ClassEntry, code: i32, message: &str) -> Result<()> {
217 throw_zend_str(ex, code, &ZendStr::new(message, false))
218}
219
220/// Throws an exception whose message is already on the Zend heap.
221fn throw_zend_str(ex: &ClassEntry, code: i32, message: &ZendStr) -> Result<()> {
222 let flags = ex.flags();
223
224 // Can't throw an interface or abstract class.
225 if flags.contains(ClassFlags::Interface) || flags.contains(ClassFlags::Abstract) {
226 return Err(Error::InvalidException(flags));
227 }
228
229 let message_ptr = message.as_c_str()?.as_ptr();
230
231 // SAFETY: We are given a reference to a `ClassEntry` therefore when we cast it
232 // to a pointer it will be valid. `message` is NUL-terminated and outlives the
233 // call; if the engine bails out here the Zend allocator reclaims it at request
234 // shutdown, as php-src does for its own copy of the message.
235 unsafe { zend_throw_exception(ptr::from_ref(ex).cast_mut(), message_ptr, code.into()) };
236 Ok(())
237}
238
239/// Throws an exception object.
240///
241/// Returns a result containing nothing if the exception was successfully
242/// thrown.
243///
244/// # Parameters
245///
246/// * `object` - The zval of type object
247///
248/// # Errors
249///
250/// * [`Error::Object`] - If the zval does not hold an object.
251///
252/// # Examples
253///
254/// ```no_run
255/// use ext_php_rs::prelude::*;
256/// use ext_php_rs::exception::throw_object;
257/// use crate::ext_php_rs::convert::IntoZval;
258///
259/// #[php_class]
260/// #[php(extends(ce = ext_php_rs::zend::ce::exception, stub = "\\Exception"))]
261/// pub struct JsException {
262/// #[php(prop, flags = ext_php_rs::flags::PropertyFlags::Public)]
263/// message: String,
264/// #[php(prop, flags = ext_php_rs::flags::PropertyFlags::Public)]
265/// code: i32,
266/// #[php(prop, flags = ext_php_rs::flags::PropertyFlags::Public)]
267/// file: String,
268/// }
269///
270/// #[php_module]
271/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
272/// module
273/// }
274///
275/// let error = JsException { message: "A JS error occurred.".to_string(), code: 100, file: "index.js".to_string() };
276/// throw_object( error.into_zval(true).unwrap() );
277/// ```
278pub fn throw_object(zval: Zval) -> Result<()> {
279 if !zval.is_object() {
280 return Err(Error::Object);
281 }
282
283 let mut zv = core::mem::ManuallyDrop::new(zval);
284 unsafe { zend_throw_exception_object(core::ptr::addr_of_mut!(zv).cast()) };
285 Ok(())
286}
287
288#[cfg(feature = "embed")]
289#[cfg(test)]
290mod tests {
291 #![allow(clippy::assertions_on_constants)]
292 use super::*;
293 use crate::embed::Embed;
294
295 #[test]
296 fn test_new() {
297 Embed::run(|| {
298 let ex = PhpException::new("Test".into(), 0, ce::exception());
299 assert_eq!(ex.message, "Test");
300 assert_eq!(ex.code, 0);
301 assert_eq!(ex.ex, ce::exception());
302 assert!(ex.object.is_none());
303 });
304 }
305
306 #[test]
307 fn test_default() {
308 Embed::run(|| {
309 let ex = PhpException::from_message("Test".into());
310 assert_eq!(ex.message, "Test");
311 assert_eq!(ex.code, 0);
312 assert_eq!(ex.ex, ce::exception());
313 assert!(ex.object.is_none());
314 });
315 }
316
317 #[test]
318 fn test_set_object() {
319 Embed::run(|| {
320 let mut ex = PhpException::from_message("Test".into());
321 assert!(ex.object.is_none());
322 let obj = Zval::new();
323 ex.set_object(Some(obj));
324 assert!(ex.object.is_some());
325 });
326 }
327
328 #[test]
329 fn test_with_object() {
330 Embed::run(|| {
331 let obj = Zval::new();
332 let ex = PhpException::from_message("Test".into()).with_object(obj);
333 assert!(ex.object.is_some());
334 });
335 }
336
337 #[test]
338 fn test_from_string() {
339 Embed::run(|| {
340 let ex: PhpException = "Test".to_string().into();
341 assert_eq!(ex.message, "Test");
342 assert_eq!(ex.code, 0);
343 assert_eq!(ex.ex, ce::exception());
344 assert!(ex.object.is_none());
345 });
346 }
347
348 #[test]
349 fn test_from_str() {
350 Embed::run(|| {
351 let ex: PhpException = "Test str".into();
352 assert_eq!(ex.message, "Test str");
353 assert_eq!(ex.code, 0);
354 assert_eq!(ex.ex, ce::exception());
355 assert!(ex.object.is_none());
356 });
357 }
358
359 #[cfg(feature = "anyhow")]
360 #[test]
361 fn test_from_anyhow() {
362 Embed::run(|| {
363 let ex: PhpException = anyhow::anyhow!("Test anyhow").into();
364 assert_eq!(ex.message, "Test anyhow");
365 assert_eq!(ex.code, 0);
366 assert_eq!(ex.ex, ce::exception());
367 assert!(ex.object.is_none());
368 });
369 }
370
371 #[test]
372 fn test_throw_ex() {
373 Embed::run(|| {
374 assert!(throw(ce::exception(), "Test").is_ok());
375
376 assert!(false, "Should not reach here");
377 });
378 }
379
380 #[test]
381 fn test_throw_with_code() {
382 Embed::run(|| {
383 assert!(throw_with_code(ce::exception(), 1, "Test").is_ok());
384
385 assert!(false, "Should not reach here");
386 });
387 }
388
389 // TODO: Test abstract class
390 #[test]
391 fn test_throw_with_code_interface() {
392 Embed::run(|| {
393 assert!(throw_with_code(ce::arrayaccess(), 0, "Test").is_err());
394 });
395 }
396
397 #[test]
398 fn test_static_throw_object_rejects_a_non_object() {
399 Embed::run(|| {
400 assert!(matches!(throw_object(Zval::new()), Err(Error::Object)));
401 });
402 }
403}