web-dev-qa-db-fra.com

Spring Boot RestController, sur le corps de réponse d'état d'erreur, le message d'erreur est vide

Sur mon démarrage Spring Boot RestController, je veux passer un message d'erreur personnalisé sur le corps de réponse en lançant une exception personnalisée. Je suivais le guide sur https://dzone.com/articles/spring-rest-service-exception-Handling-1

Ce sont mes extraits de code:

UsernotFoundException

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;


@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(String message) {
        super(message);
    }
}

Le rescrecteur de repos simplifié

@RestController
public class CreateRfqController {

    @PostMapping("api/create-rfq")
    public ResponseEntity<Rfq> newRfq(@RequestBody Rfq newRfq) {
        throw new UserNotFoundException("User Not Found");
    }
}

Lorsque vous appelez mon API de repos, j'ai toujours un message vide:

{
    "timestamp": "2020-06-24T18:23:30.846+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "",
    "path": "/api/create-rfq"
}

au lieu de cela, je veux "message": "User Not Found",

À une étape, je le faisais même travailler. On dirait que je me suis gâché sur un point.

Dans le journal, vous pouvez même voir l'utilisateur non trouvé de texte et de la classe d'exception correcte.

24 Jun 2020;20:50:52.998 DEBUG = 145: o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolved [configRestServer.exceptions.UserNotFoundException: User Not Found]
24 Jun 2020;20:50:52.998 DEBUG = 1131: o.s.w.s.DispatcherServlet - Completed 404 NOT_FOUND
24 Jun 2020;20:50:53.003 DEBUG = 91: o.s.w.s.DispatcherServlet - "ERROR" dispatch for POST "/error", parameters={}
24 Jun 2020;20:50:53.006 DEBUG = 414: o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
24 Jun 2020;20:50:53.018 DEBUG = 265: o.s.w.s.m.m.a.HttpEntityMethodProcessor - Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
24 Jun 2020;20:50:53.018 DEBUG = 91: o.s.w.s.m.m.a.HttpEntityMethodProcessor - Writing [{timestamp=Wed Jun 24 20:50:53 CEST 2020, status=404, error=Not Found, message=, path=/api/create-rf (truncated)...]
24 Jun 2020;20:50:53.038 DEBUG = 1127: o.s.w.s.DispatcherServlet - Exiting from "ERROR" dispatch, status 404

ma construction.Gradle

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }

// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '2.3.0.RELEASE'

// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.3.1.RELEASE'

compile group: 'org.Apache.commons', name: 'commons-lang3', version: '3.9'

    runtime group: 'com.Oracle', name: 'ojdbc6', version: '11.2.0.3'

    compile group: 'com.Sun.mail', name: 'javax.mail', version: '1.6.2'

// https://mvnrepository.com/artifact/org.Apache.httpcomponents/httpclient
    compile group: 'org.Apache.httpcomponents', name: 'httpclient', version: '4.5.12'

Mise à jour: Affirmez exprès, j'ai passé un type de variable incorrect dans mon objet RFQ pour produire une erreur par défaut. Même ici dans la réponse, le message est vide:

{
    "timestamp": "2020-06-24T19:20:18.831+00:00",
    "status": 403,
    "error": "Forbidden",
    "message": "",
    "path": "/api/create-rfq"
}
9
Hannes Roth

Créez un pojo pour représenter votre réponse "message": "User Not Found"

public class ExceptionMessage {
    String message;
    String details;

    public ExceptionMessage(String message, String details) {
        this.message = message;
        this.details = details;
    }
  //Add getters and setters
}

Puis ajoutez une classe de conseil du contrôleur qui enverra la réponse.

@ControllerAdvice
public class CustomException {
    @ExceptionHandler(UserNotFoundException.class)
    public final ResponseEntity<ExceptionMessage> UserNotFoundException(UserNotFoundException ex, WebRequest request) {
        ExceptionMessage error = new ExceptionMessage("Not found", ex.getMessage());
        return new ResponseEntity<ExceptionMessage>(error, HttpStatus.BAD_REQUEST);
    }

}

0
Zishan Khan