如何处理Java SpringBoot中的HttpMediaTypeNotAcceptableException?

How to handle HttpMediaTypeNotAcceptableException in Java SpringBoot?

提问人:1449piotr 提问时间:8/30/2023 最后编辑:The Coding Penguin1449piotr 更新时间:8/31/2023 访问量:23

问:

当我添加 HTTP 标头时,我的应用程序会在控制台中返回空内容。我不知道如何处理它才能得到这样的响应:"Accept": "application/xml"HttpMediaTypeNotAcceptableException

{
    "status": 406,
    "message": "{message}"
}

这是我尝试捕获此错误的控制器类,但这不起作用。我也尝试使用注释,但它似乎也不起作用。@ExceptionHandler

package com.example.zadanie.controller;

import com.example.zadanie.model.ErrorModel;
import com.example.zadanie.model.RepoModel;
import com.example.zadanie.service.RepoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpMediaTypeException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;

import java.util.List;

@org.springframework.stereotype.Controller
public class Controller {
    private RepoService repoService;

    @Autowired
    public Controller(RepoService repoService) {
        this.repoService = repoService;
    }

    @GetMapping("/{username}")
    public ResponseEntity<List<RepoModel>> getRepoList(@PathVariable String username) {
        try {
            return new ResponseEntity(repoService.repoModels(username), HttpStatus.OK);
        }
        catch (HttpClientErrorException e) {
            ErrorModel errorModel = new ErrorModel(e.getStatusCode().value(), "user does not exist");
            return new ResponseEntity(errorModel, HttpStatus.NOT_FOUND);
        }
    }

//    @GetMapping
//    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
//    public ResponseEntity httpMediaTypeNotAcceptableExceptionHandler(){
//        return new ResponseEntity(new ErrorModel(HttpStatus.NOT_ACCEPTABLE.value(), "this application accept only json response"),HttpStatus.NOT_ACCEPTABLE);
//    }
}

服务等级

在这里,我从 github 及其 API 下载存储库。

package com.example.zadanie.service;

import com.example.zadanie.model.RepoModel;
import com.example.zadanie.model.ResponseModel;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class RepoService {

    public List<ResponseModel> repoModels(String username){
        List<ResponseModel> responseModelList = new ArrayList<>();
        RestTemplate restTemplate = new RestTemplate();

            RepoModel[] repoModels = restTemplate.getForObject("https://api.github.com/users/" + username + "/repos", RepoModel[].class);
            for (RepoModel repoModel : repoModels) {
                ResponseModel responseModel = new ResponseModel();
                responseModel.setName(repoModel.getName());
                responseModel.setLogin(repoModel.getOwner().getLogin());
                responseModelList.add(responseModel);
            }
            return responseModelList;
    }


}

ErrorModel 类

package com.example.zadanie.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;

public class ErrorModel {
    @JsonProperty("status")
    private int httpStatusCode;
    @JsonProperty("message")
    private String message;

    public ErrorModel() {
    }

    public ErrorModel(int httpStatusCode, String message) {
        this.httpStatusCode = httpStatusCode;
        this.message = message;
    }

    public int getHttpStatusCode() {
        return httpStatusCode;
    }

    public void setHttpStatusCode(int httpStatusCode) {
        this.httpStatusCode = httpStatusCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "ErrorModel{" +
                "httpStatusCode=" + httpStatusCode +
                ", message='" + message + '\'' +
                '}';
    }
}

我怎样才能以正确的方式处理这个异常,并得到一个像前面所示的输出格式?

java spring-boot 异常 http-status-code-406

评论


答: 暂无答案