|
| 1 | +# Exceptions |
| 2 | + |
| 3 | +Exceptions can be thrown from Rust to PHP. The inverse (catching a PHP exception |
| 4 | +in Rust) is currently being worked on. |
| 5 | + |
| 6 | +## Throwing exceptions |
| 7 | + |
| 8 | +[`PhpException`] is the type that represents an exception. It contains the |
| 9 | +message contained in the exception, the type of exception and a status code to |
| 10 | +go along with the exception. |
| 11 | + |
| 12 | +You can create a new exception with the `new()`, `default()`, or |
| 13 | +`from_class::<T>()` methods. `Into<PhpException>` is implemented for `String` |
| 14 | +and `&str`, which creates an exception of the type `Exception` with a code of 0. |
| 15 | +It may be useful to implement `Into<PhpException>` for your error type. |
| 16 | + |
| 17 | +Calling the `throw()` method on a `PhpException` attempts to throw the exception |
| 18 | +in PHP. This function can fail if the type of exception is invalid (i.e. does |
| 19 | +not implement `Exception` or `Throwable`). Upon success, nothing will be |
| 20 | +returned. |
| 21 | + |
| 22 | +`IntoZval` is also implemented for `Result<T, E>`, where `T: IntoZval` and |
| 23 | +`E: Into<PhpException>`. If the result contains the error variant, the exception |
| 24 | +is thrown. This allows you to return a result from a PHP function annotated with |
| 25 | +the `#[php_function]` attribute. |
| 26 | + |
| 27 | +### Examples |
| 28 | + |
| 29 | +```rust |
| 30 | +# extern crate ext_php_rs; |
| 31 | +use ext_php_rs::prelude::*; |
| 32 | +use std::convert::TryInto; |
| 33 | + |
| 34 | +// Trivial example - PHP represents all integers as `u64` on 64-bit systems |
| 35 | +// so the `u32` would be converted back to `u64`, but that's okay for an example. |
| 36 | +#[php_function] |
| 37 | +pub fn something_fallible(n: u64) -> PhpResult<u32> { |
| 38 | + let n: u32 = n.try_into().map_err(|_| "Could not convert into u32")?; |
| 39 | + Ok(n) |
| 40 | +} |
| 41 | + |
| 42 | +#[php_module] |
| 43 | +pub fn module(module: ModuleBuilder) -> ModuleBuilder { |
| 44 | + module |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +[`PhpException`]: https://docs.rs/ext-php-rs/0.5.0/ext_php_rs/php/exceptions/struct.PhpException.html |
0 commit comments