自定义主体错误消息-Spring Boot REST

时间:2019-05-24 15:52:11

标签: java spring rest spring-boot

我正在尝试自定义我的身体错误消息。

我的springboot版本是2.1.5.RELEASE

我想要这个:

{
"This should be application specific"
}

但是我收到了:

{
    "timestamp": "2019-05-24T15:47:10.872+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Not Found (404)",
    "path": "/github/gifojhuinh4w5"
}

我的异常类是:

@ControllerAdvice
public class AppExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    protected ResponseEntity<Object> handleConflict(Exception ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse,
                new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }
}

捕获异常的我的班级

@Controller
@EnableAutoConfiguration
public class GitHub {

    @RequestMapping(value ="/github/{usuario}", produces = "application/json; charset=UTF-8")
    @ResponseBody
    public ResponseEntity<Object> quantidadeRepositorios(@PathVariable(value = "usuario")String usuario) throws IOException {

        HashMap<String, Integer> map = new HashMap<>();
        RepositoryService service = new RepositoryService();
        GitHubClient client = new GitHubClient();
        Gson gson = new Gson();
        client.setOAuth2Token("key");

        map.put("Total",service.getRepositories(usuario).size()); // exception captured here

        return new ResponseEntity<>(gson.toJson(map), HttpStatus.OK);
    }
}

1 个答案:

答案 0 :(得分:0)

当ExceptionHandler捕获到异常时,构建一个响应实体并按如下所示返回它。

创建一个ErrorResponseDTO对象并将消息设置为该对象。

public class ErrorResponseDTO {

    private String errorMessage;

}

在异常处理程序中,返回该dto对象。

    @ExceptionHandler(Exception.class)
    protected ResponseEntity<Object> handleConflict(Exception ex, WebRequest request) {
        ErrorResponseDTO errorDTO = new ErrorResponseDTO();
        errorDTO.setErrorMessage("This should be application specific");
        return new ResponseEntity<>(errorDTO, HttpStatus.INTERNAL_SERVER_ERROR);
    }

这将为您提供所需的有效载荷。

{
"This should be application specific"
}