如何在spring中添加带有错误消息的HTTP状态代码

时间:2018-02-15 14:51:44

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

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

这是我的代码段

DepartmentModel

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

DepartmentRepository

@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();
    }

DepartmentService

@Service
    public class DepartmentService
    {   
        @Autowired
        DepaertmentRepository depRepo;

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

        }   
    }

DepartmentController

@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)

1 个答案:

答案 0 :(得分:1)

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

@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

<强>更新

有必要将@ControllerAdvice注释添加到扩​​展ResponseEntityExceptionHandler的类中。