Skip to content

Commit fb48139

Browse files
committed
Sorry, something went wrong.
0 parents  commit fb48139

9 files changed

Lines changed: 293 additions & 0 deletions

.editorconfig

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# For more information about the properties used in
2+
# this file, please see the EditorConfig documentation:
3+
# http://editorconfig.org/
4+
5+
[*]
6+
charset = utf-8
7+
end_of_line = lf
8+
indent_size = 4
9+
indent_style = space
10+
insert_final_newline = true
11+
trim_trailing_whitespace = true
12+
13+
[*.md]
14+
trim_trailing_whitespace = false
15+
16+
[*.{yml,js,json,css,scss,eslintrc}]
17+
indent_size = 2
18+
indent_style = space
19+
20+
[composer.json]
21+
indent_size = 4

LICENSE.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2018 Jonathon Menz
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# SilverStripe Custom Errors Module
2+
3+
## Overview
4+
5+
As an alternative to the Error Page module, this module provides themed error responses but makes developers responsible for the content of error messages instead of CMS users.
6+
7+
## Installation
8+
9+
```
10+
$ composer require jonom/silverstripe-custom-errors
11+
```
12+
13+
## Configuration
14+
15+
You can define default response content for each response code through the yml config API. Response codes need to be prefixed with the letter 'e' because numbers alone aren't valid SS config keys. Fields you specify will be passed through to a page template for rendering. You can specify a value only, or cast a value by specifying details in an arrray. Example:
16+
17+
```yaml
18+
---
19+
Name: my-custom-errors
20+
After:
21+
- '#custom-errors'
22+
---
23+
JonoM\CustomErrors\CustomErrorControllerExtension:
24+
custom_fields:
25+
default:
26+
Content:
27+
Type: 'SilverStripe\ORM\FieldType\DBHTMLText'
28+
Value: '<p>Sorry, there was a problem with handling your request.</p>'
29+
e404:
30+
Title: 'Not Found'
31+
Content:
32+
Type: 'SilverStripe\ORM\FieldType\DBHTMLText'
33+
Value: '<p>Sorry, it seems you were trying to access a page that doesnʼt exist.</p><p>Please check the spelling of the URL you were trying to access and try again.</p>'
34+
```
35+
36+
You can also specify a default controller and template for error responses.
37+
38+
```yaml
39+
JonoM\CustomErrors\CustomErrorControllerExtension:
40+
default_controller: 'PageController'
41+
default_template: 'Page' # exclude .ss extension
42+
```
43+
44+
## Custom error responses
45+
46+
You can call `$this->httpError($statusCode, $errorMessage)` from your controller and get a themed response, but if default content has been provided for the given status code, your `$errorMessage` won't be displayed. This is to ensure that you have some control over all of the error messages that a user may see, not just the ones that are triggered in your own code.
47+
48+
To return a custom error response from a controller, instead of calling `$this->httpError()` you can use `$this->customError()` and pass through custom fields the same way you would if using `renderWith()`. Example:
49+
50+
```php
51+
if ($somethingWentWrong) {
52+
$this->customError(404, [
53+
'Title' => 'We couldn\'t find the droids you are looking for',
54+
'Content' => DBField::create_field('HTMLText', '<p>Please try another Cantina</p>')
55+
]);
56+
}
57+
```
58+
59+
Any fields you specify are merged with the defaults, so you only need to specify fields that you want to override.
60+
61+
```php
62+
$this->customError(404, [
63+
'Content' => DBField::create_field('HTMLText', '<p>Maybe try the Google</p>')
64+
]);
65+
```
66+
67+
You can also specify a controller and template to be used.
68+
69+
```php
70+
$this->customError(
71+
404,
72+
[
73+
'Content' => DBField::create_field('HTMLText', '<p>Here are some other droids you may be interested in:</p>'),
74+
'Droids' => Droid::get()->filterAny(['Language' => 'Beeps', 'Color' => 'Gold'])->limit(5)
75+
],
76+
'DroidHolder',
77+
'DroidHolderController'
78+
);
79+
```
80+
81+
## Maintainer contact
82+
83+
[jonathonmenz.com](http://jonathonmenz.com)

_config/custom-errors.yml

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
Name: custom-errors
3+
---
4+
JonoM\CustomErrors\CustomErrorControllerExtension:
5+
default_controller: 'PageController'
6+
default_template: 'Page' # exclude .ss extension
7+
custom_fields:
8+
default:
9+
Content:
10+
Type: 'SilverStripe\ORM\FieldType\DBHTMLText'
11+
Value: '<p>Sorry, there was a problem with handling your request.</p>'
12+
e404:
13+
Title: 'Not Found'
14+
Content:
15+
Type: 'SilverStripe\ORM\FieldType\DBHTMLText'
16+
Value: '<p>Sorry, it seems you were trying to access a page that doesnʼt exist.</p><p>Please check the spelling of the URL you were trying to access and try again.</p>'
17+
e500:
18+
Title: 'Internal Server Error'
19+
Content:
20+
Type: 'SilverStripe\ORM\FieldType\DBHTMLText'
21+
Value: '<p>Sorry, there was a problem with handling your request.</p>'

_config/extensions.yml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
Name: custom-errors-extensions
3+
---
4+
SilverStripe\Control\Controller:
5+
extensions:
6+
- JonoM\CustomErrors\CustomErrorControllerExtension
7+
SilverStripe\Forms\Form:
8+
extensions:
9+
- JonoM\CustomErrors\CustomErrorControllerExtension

code-of-conduct.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
When having discussions about this module in issues or pull request please adhere to the [SilverStripe Community Code of Conduct](https://docs.silverstripe.org/en/contributing/code_of_conduct).

composer.json

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
{
2+
"name": "jonom/silverstripe-custom-errors",
3+
"description": "Themed custom error responses for SilverStripe CMS",
4+
"type": "silverstripe-vendormodule",
5+
"license": "MIT",
6+
"keywords": [
7+
"silverstripe",
8+
"error",
9+
"errorpage"
10+
],
11+
"authors": [
12+
{
13+
"name": "Jonathon Menz",
14+
"homepage": "http://jonathonmenz.com"
15+
}
16+
],
17+
"require": {
18+
"silverstripe/vendor-plugin": "^1.0",
19+
"silverstripe/cms": "^4"
20+
},
21+
"replace": {
22+
"silverstripe/errorpage":"*"
23+
},
24+
"autoload": {
25+
"psr-4": {
26+
"JonoM\\CustomErrors\\": "src/"
27+
}
28+
},
29+
"extra": {
30+
"installer-name": "custom-errors"
31+
},
32+
"minimum-stability": "dev",
33+
"prefer-stable": true
34+
}

contributing.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Contributing
2+
- Maintenance on this module is a shared effort of those who use it
3+
- To contribute improvements to the code, ensure you raise a pull request and discuss with the module maintainers
4+
- Please follow the SilverStripe [code contribution guidelines](https://docs.silverstripe.org/en/contributing/code/) and [Module Standard](https://docs.silverstripe.org/en/developer_guides/extending/modules/#module-standard)
5+
- Supply documentation that follows the [GitHub Flavored Markdown](https://help.github.com/articles/markdown-basics/) conventions
6+
- When having discussions about this module in issues or pull request please adhere to the [SilverStripe Community Code of Conduct](https://docs.silverstripe.org/en/contributing/code_of_conduct/)
7+
8+
## Contributor license agreement
9+
By supplying code to this module in patches, tickets and pull requests, you agree to assign copyright
10+
of that code to Jonathon Menz, on the condition that these code changes are released under the
11+
same MIT license as the original module. We ask for this so that the ownership in the license is clear
12+
and unambiguous. By releasing this code under a permissive license such as MIT, this copyright assignment
13+
won't prevent you from using the code in any way you see fit.
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
<?php
2+
3+
namespace JonoM\CustomErrors;
4+
5+
use Page;
6+
use PageController;
7+
use SilverStripe\Control\Director;
8+
use SilverStripe\Control\HTTPResponse;
9+
use SilverStripe\Control\HTTPResponse_Exception;
10+
use SilverStripe\Core\Config\Configurable;
11+
use SilverStripe\Core\Extension;
12+
use SilverStripe\Forms\TextField;
13+
use SilverStripe\ORM\FieldType\DBField;
14+
use SilverStripe\ORM\FieldType\DBHTMLText;
15+
16+
/**
17+
* Enhances error handling for a controller with themed output
18+
*
19+
* Precedence: error messages passed in $controller->httpError() will only be used if no yml config content is available. Use $controller->customError() to render an error response with custom content.
20+
*/
21+
class CustomErrorControllerExtension extends Extension
22+
{
23+
use Configurable;
24+
25+
private static $custom_fields = [];
26+
27+
private static $default_controller = '';
28+
29+
private static $default_template = '';
30+
31+
/**
32+
* Used by {@see RequestHandler::httpError}
33+
*
34+
* @param int $statusCode
35+
* @param HTTPRequest $request
36+
* @param string $errorMessage
37+
* @throws HTTPResponse_Exception
38+
*/
39+
public function onBeforeHTTPError($errorCode, $request, $errorMessage = null)
40+
{
41+
// Use provided error message only if no content is specified in yml config. This is because the error messages used in non-user code when calling ->httpError may not be suitable to show to a user.
42+
$customFields = [];
43+
if (!isset($this->config()->get('custom_fields')['e' .$errorCode])) $customFields['Content'] = $errorMessage;
44+
return $this->customError($errorCode, $customFields);
45+
}
46+
47+
public function defaultCustomFieldsFor($errorCode)
48+
{
49+
// Get content from yml config for a default
50+
$defaultCustomFields = [];
51+
$configCustomFields = $this->config()->get('custom_fields');
52+
$configCustomFields = isset($configCustomFields['e' . $errorCode]) ? $configCustomFields['e' . $errorCode] : $configCustomFields['default'];
53+
foreach ($configCustomFields as $fieldName => $fieldInfo) {
54+
// Create a db field if type is specified, otherwise pass plain text
55+
if (is_array($fieldInfo)) {
56+
$defaultCustomFields[$fieldName] = DBField::create_field($fieldInfo['Type'], $fieldInfo['Value']);
57+
} else {
58+
$defaultCustomFields[$fieldName] = $fieldInfo;
59+
}
60+
}
61+
return $defaultCustomFields;
62+
}
63+
64+
65+
public function customError($errorCode, $customFields, $template = null, $controllerType = null)
66+
{
67+
// Simple/default response if ajax
68+
if (Director::is_ajax()) {
69+
throw new HTTPResponse_Exception($errorMessage, $errorCode);
70+
}
71+
// Otherwise build a themed response
72+
if (!$controllerType) $controllerType = $this->config()->get('default_controller');
73+
if (!$template) $template = $this->config()->get('default_template');
74+
$defaultCustomFields = $this->defaultCustomFieldsFor($errorCode);
75+
$response = new HTTPResponse();
76+
$response->setStatusCode($errorCode);
77+
// Set some default properties, then override with custom ones if provided
78+
$customFields = array_merge(
79+
// Use title from config if set, otherwise fall back to framework definition
80+
['Title' => $response->getStatusDescription()],
81+
$defaultCustomFields,
82+
$customFields
83+
);
84+
$body = $controllerType::create()->renderWith($template, $customFields);
85+
$response->setBody($body);
86+
if ($response) {
87+
throw new HTTPResponse_Exception($response, $errorCode);
88+
}
89+
}
90+
}

0 commit comments

Comments
 (0)