亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

自定義正文錯誤消息 - 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 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號