Home > Mobile >  Easiest way to return a custom ResponseEntity<>(HttpStatus.BAD_REQUEST) with custom message ?
Easiest way to return a custom ResponseEntity<>(HttpStatus.BAD_REQUEST) with custom message ?

Time:04-01

It's the first time i develop an api REST spring boot.

I want to return a custom message when i have Bad Request 400

Hi,

It's the first time i develop an api REST spring boot.

I have my controller :

 @GetMapping("/DetailDossier/{id},{parameters}/")

    public ResponseEntity<List<DetailDossierRspn>> DetailDossierQstn(
            @PathVariable(value = "id") String[] id, @PathVariable(value = "parameters") String parameters,
             throws ParseException {

    
        List<DetailDossierRspn> rspn = new ArrayList<>();

        WSDetailDossierService mainDAO = new WSDetailDossierService();

    // If Sql result return -> List<DetailDossierRspn>

    // If no sql result return null

        rspn = mainDAO.initialiserDAO(identifiant, coetb, null);
        if (rspn == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } else {
            return ResponseEntity.ok(rspn);
        }
    }

I want the easiest way to return a error 400 :

ResponseEntity<>(HttpStatus.BAD_REQUEST)

with a custom message.

I tried to create a @ControllerAdvice but it didn't work because my my controller return a List<Object>

There is a way to do easy custom message ?

Thanks ;)

CodePudding user response:

You need to create a custom @ControllerAdvice:

Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller classes.

extending ResponseEntityExceptionHandler:

A convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods.

Basically something like:

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<>("my custom message", status);
    }

}
  • Related