【问题标题】:How to add HTTP status code with error message in spring如何在春季添加带有错误消息的HTTP状态代码
【发布时间】:2018-02-17 19:51:59
【问题描述】:

我创建了一个 spring data jpa 应用程序。在这个应用程序中,我的方法请求是 GET。但如果我试图访问该方法请求 url 作为发布请求。在这种情况下,我想知道如何在我的自定义错误消息中添加 HTTP 状态代码 405(Method Not Allowed)。

这是我的代码 sn-p

部门模型

package com.demo.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "department")
public class DepartmentModel implements Serializable {  

    private static final long serialVersionUID = 1L;
     @Id         
    public  Integer ndeptid;    
    public String sdeptname ;
    public  Integer ninstid  ;
    public Boolean bislocked;
    public String sclientdeptid;
    public Integer nsurveymethodid;
    public Boolean bisjointuse;
    public Integer ntempdeptid;
    public  Boolean balternatejointusepercentage;
    public Integer ndivid;
    //getter and setter

部门存储库

@Repository
public interface DepaertmentRepository extends JpaRepository<DepartmentModel, Integer>
{
    @Query("select new map(dep.sdeptname as sdeptname)"
            + " from DepartmentModel as dep where dep.ninstid=60")  
    Set<DepartmentModel> findBySDepName();
    }

部门服务

@Service
    public class DepartmentService
    {   
        @Autowired
        DepaertmentRepository depRepo;

        public   Set<DepartmentModel> findDepName()
        {
            return depRepo.findBySDepName();

        }   
    }

部门主管

@RestController
@RequestMapping("/SpaceStudy/SpaceAdmin")
public class DepartmentController {

    @Autowired
    DepartmentService depService;


    @CrossOrigin(origins="*")
    @GetMapping("AccountMaintenance/LoadDepartment")
    //@ResponseStatus( value = HttpStatus.METHOD_NOT_ALLOWED) 
    public  Set<DepartmentModel> findDepName() {

            return depService.findDepName();
    }
}

当我以帖子形式访问 GET 请求时,任何人都可以帮助我如何添加带有正确消息的 HTTP 状态代码 (405)

【问题讨论】:

    标签: spring-data-jpa http-status-code-405


    【解决方案1】:

    您可以覆盖ResponseEntityExceptionHandler 的方法handleHttpRequestMethodNotSupported 并实现您自己的错误消息对象。例如:

    @Override
    protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest req) {
    
        headers.setAllow(ex.getSupportedHttpMethods());
        ErrorMessage errorMessage = ErrorMessage.of(
                status.value(), 
                "You cannot make this request - the method is not allowed!", 
                ex.getMessage(), 
                ((ServletWebRequest) req).getRequest().getServletPath() 
        );
        return new ResponseEntity<>(errorMessage, headers, status);
    }
    
    @Value(staticConstructor = "of")
    private static class ErrorMessage {
        private Instant timestamp = Instant.now();
        private Integer status;
        private String error;
        private String message;
        private String path;
    }
    

    查看我的完整版demo 了解更多信息。

    您不仅可以覆盖 ResponseEntityExceptionHandler 的这个方法,还可以覆盖所有剩余的方法来自定义处理其他异常。

    注意:您可以使用另一种方法来处理异常(或同时使用两者) - 实现 exception handler

    更新

    扩展ResponseEntityExceptionHandler的类需要添加@ControllerAdvice注解。

    【讨论】:

    • 使用这段代码我可以处理异常。如果我在处理异常之前没有错,我们需要从 service.how to throw that exception 中抛出该异常
    • @R.Shinde 你不需要抛出异常——Spring 自己做。只需使用一种方法(例如 GET "/people")创建一个简单的控制器,然后请求 GET "/users"。您将看到带有相应异常的错误消息...
    • 我尝试过这样,但它给了我默认错误消息 404(未找到)
    • 我在询问不支持的方法(尝试访问帖子而不是获取)。我想你说的是错误的 URL
    • @R.Shinde 尝试请求 'POST /people' 而不是 GET(很难记住所有变体))。查看ResponseEntityExceptionHandler 的其余方法 - 您可以全部覆盖它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    相关资源
    最近更新 更多