0

I am trying to throw a 403 (Forbidden error) in my controller. When the exception is thrown, I would like to display the associated view. I was under the assumption that if the error is one of the built in exceptions, this would be pretty easy. I throw the exception like this:

 throw new ForbiddenException("You do not have permission to view this page.");

I also created a view called "error403.ctp" in the app/view/Errors folder (it already contained 400 and 500). The problem is that when the error is thrown, it displays the error400.ctp view instead. Do I have to create custom exceptions for a built in error? What am I doing wrong.

Cœur
  • 37,241
  • 25
  • 195
  • 267
jason
  • 3,821
  • 10
  • 63
  • 120

2 Answers2

1

From http://book.cakephp.org/2.0/en/development/exceptions.html#exception-renderer

"For all 4xx and 5xx errors the view files error400.ctp and error500.ctp are used respectively."

So you aren't doing anything wrong, that's just the default CakePHP behavior. As to how to change it so that you can have a 403 page separate from the other 4XX errors, see CakePHP 2.0 - How to make custom error pages?

Community
  • 1
  • 1
Kai
  • 3,803
  • 1
  • 16
  • 33
0

I don't have the exact cake version you are using, so I'll use links to docs of version 2.3, but it should apply to any version 2.x.

If you look at the default ExceptionRenderer construct, you get this from the description

Creates the controller to perform rendering on the error response. If the error is a CakeException it will be converted to either a 400 or a 500 code error depending on the code used to construct the error.

And clear enough, from the code of that function, all errors get mapped to that:

$method = 'error500';
if ($code >= 400 && $code < 500) {
    $method = 'error400';
}

You'll have to create a custom Exception Renderer if you want to use other views. Also, keep in mind that when using debug < 1, you'll only get 500 error pages

Captures and handles all unhandled exceptions. Displays helpful framework errors when debug > 1. When debug < 1 a CakeException will render 404 or 500 errors. If an uncaught exception is thrown and it is a type that ExceptionHandler does not know about it will be treated as a 500 error.

Nunser
  • 4,512
  • 8
  • 25
  • 37