为了账号安全,请及时绑定邮箱和手机立即绑定

自定义正文错误消息 - Spring boot REST

自定义正文错误消息 - Spring boot REST

慕标5832272 2022-12-15 15:03:58
我正在尝试自定义我的正文错误消息。我的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"}我的异常类是:@ControllerAdvicepublic 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@EnableAutoConfigurationpublic 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 回答

?
智慧大石

TA贡献1946条经验 获得超3个赞

当 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"

}


查看完整回答
反对 回复 2022-12-15
  • 1 回答
  • 0 关注
  • 75 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信