PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label httpresponse. Show all posts
Showing posts with label httpresponse. Show all posts

Friday, August 5, 2022

[FIXED] When to use ResponseStatusException and ControllerAdvice

 August 05, 2022     controller-advice, error-handling, exception, httpresponse, response     No comments   

Issue

Spring5 has introduced ResponseStatusException, which has put me in a dilemma as to in what scenario I can use a ResponseStatusException and ControllerAdvice as both of them are quiet similar.

Can anyone help me with this. Thanks in advance.


Solution

Lets first understand what is ResponseStatusException and ControllerAdvice

ResponseStatusException is a programmatic alternative to @ResponseStatus and is the base class for exceptions used for applying a status code to an HTTP response.

@GetMapping("/actor/{id}")
public String getActorName(@PathVariable("id") int id) {
    try {
        return actorService.getActor(id);
    } catch (ActorNotFoundException ex) {
        throw new ResponseStatusException(
          HttpStatus.NOT_FOUND, "Actor Not Found", ex);
    }
}

The @ControllerAdvice annotation allows us to consolidate multiple, scattered @ExceptionHandlers into a single, global error handling component.

@ControllerAdvice
public class RestResponseEntityExceptionHandler 
  extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value 
      = { IllegalArgumentException.class, IllegalStateException.class })
    protected ResponseEntity<Object> handleConflict(
      RuntimeException ex, WebRequest request) {
        return ResponseEntity<Object>;
    }
}

Coming back to your questions of when to use what:

  1. If you want to provide a unified and global way of exception handling make use of ControllerAdvice. It also eliminates code duplication which might be caused by ResponseStatusException.
  2. In order to throw different error code and responses for the same exception, don't want to create custom exception classes and to avoid tight coupling make use of ResponseStatusException.

References:

  1. Spring ResponseStatusException

  2. Error Handling for REST with Spring



Answered By - Anjan Krishna
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, April 15, 2022

[FIXED] How would set a response header X-Frame-Options?

 April 15, 2022     html, httpresponse, iframe, response     No comments   

Issue

I need help with setting a response header for my site, hosted on Github pages. How would I set the X-Frame-Options option to DENY? I could use HTML, CSS, JS, or PHP.

I have tried using <meta http-equiv="X-Frame-Options" content="deny"> but I got this message in console:

X-Frame-Options may only be set via an HTTP header sent along with a document. It may not be set inside <meta>.

UPDATE

Since I can not edit the headers because my site is hosted on GitHub, is there a way to check if the page is in an iframe and display an image instead of the content?

Any ideas are appreciated!


Solution

You can't.

Github pages does not provide any mechanism for customising HTTP response headers (including running server-side code in any programming language).



Answered By - Quentin
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, January 10, 2022

[FIXED] CakePHP 3 Http Client timeout error handling

 January 10, 2022     cakephp, cakephp-3.0, httpresponse, php     No comments   

Issue

I'm trying to use the CakePHP 3 Http Client to check urls for their response status code (404, 301, 200 etc)

$http = new Client();
$response = $http->get($links[$i]['url'],[],['timeout' => '10']);
$links[$i]['http_status'] = $response->statusCode();

However, if I come across a url that timesout, the entire script fails. I'm having trouble figuring out how to add error handling so that if it does timeout, I can log it and move on.

Any ideas?


Solution

The solution was to use try/catch. I had tried this initially but missed the \ before Exception on the catch

try {
    // code
} catch (\Exception $e) {
    // error
}


Answered By - Sanfly
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, January 9, 2022

[FIXED] JSON exception in cakephp 3

 January 09, 2022     cakephp-3.0, exception, httpresponse, json     No comments   

Issue

I'm doing a restfull api in cakephp... And sometime i have some throw exceptions. For example:

if (!$this->request->is('post')) {
            throw new MethodNotAllowedException("The requested resource does not support http method " . $this->request->param('_method'));
        }

My problem is when the url is /controller/action.json the response is :

{
message: "The requested resource does not support http method GET",
url: "/api/auth/users/authenticate.json",
code: 405
}

In json format, but, when my url is /controller/action. My response is HTML, i want to know if is possible to force these exceptions to be always json without putting .json in the url.

Thanks!


Solution

You can force exceptions to be always rendered in json adding in Controller/ErrorController.php (in beforeRender)

$this->RequestHandler->renderAs($this, 'json');


Answered By - fiblan
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, December 30, 2021

[FIXED] How to output custom HTTP body contents with CakePHP 3.4? Echoing causes "Unable to emit headers" error

 December 30, 2021     cakephp, cakephp-3.4, cakephp-3.x, httpresponse, php     No comments   

Issue

Using CakePHP 3.4, PHP 7.0.

I'm attempting to do a really simple controller method to output some JSON. It is outputting "Cannot modify headers...".

public function test() {
    $this->autoRender = false;
    echo json_encode(['method' => __METHOD__, 'class' => get_called_class()]);
}

Browser output

{"method":"App\\Controller\\SomeController::test", "class":"App\\Controller\\SomeController"}

Warning (512): Unable to emit headers. Headers sent in file=...
Warning (2): Cannot modify header information - headers already sent by (output started at ...)
Warning (2): Cannot modify header information - headers already sent by (output started at ...)

I fully understand why PHP complains about this. The question is why does CakePHP complain and what can I do about it?

It should be noted that CakePHP 2.x allowed this.


Solution

Controllers should never echo data! Echoing data can lead to all kinds of problems, from the data not being recognized in the test environment, to headers not being able to be sent, and even data being cut off.

Doing it that way was already wrong in CakePHP 2.x, even though it might have worked in some, maybe even most situations. With the introduction of the new HTTP stack, CakePHP now explicitly checks for sent headers before echoing the response, and will trigger an error accordingly.

The proper way to send custom output was to configure and return the response object, or to use serialized views, and it's still the same in 3.x.

Quote from the docs:

Controller actions generally use Controller::set() to create a context that View uses to render the view layer. Because of the conventions that CakePHP uses, you don’t need to create and render the view manually. Instead, once a controller action has completed, CakePHP will handle rendering and delivering the View.

If for some reason you’d like to skip the default behavior, you can return a Cake\Network\Response object from the action with the fully created response.

* As of 3.4 that would be \Cake\Http\Response

Cookbook > Controllers > Controller Actions

Configure the response

Using the PSR-7 compliant interface

$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]);

$this->response = $this->response->withStringBody($content);
$this->response = $this->response->withType('json');
// ...

return $this->response;

The PSR-7 compliant interface uses immutable methods, hence the utilization of the return value of withStringBody() and withType(). In CakePHP < 3.4.3, withStringBody() is not available, and you can instead directly write to the body stream, which will not change the state of the response object:

$this->response->getBody()->write($content);

Using the deprecated interface

$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]);

$this->response->body($content);
$this->response->type('json');
// ...

return $this->response;

Use a serialized view

$content = ['method' => __METHOD__, 'class' => get_called_class()];

$this->set('content', $content);
$this->set('_serialize', 'content');

This requires to also use the request handler component, and to enable extensing parsing and using correponsing URLs with .json appended, or to send a proper request with a application/json accept header.

See also

  • Cookbook > Controllers > Controller Actions
  • Cookbook > Request & Response Objects > Setting the Body
  • Cookbook > Views > JSON and XML views
  • PHP FIG Standards > PSR-7 HTTP message interfaces


Answered By - ndm
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing