我是Java领域的新手。
我想在调用参数时丢失错误并从正文中获取错误消息(例如,标题)。但是我不能。
我附加了我的全部代码,在MovieListController.java文件中,我使用if / else条件语句来引发异常。
实际上,我对Java还没有太多的了解。因此,请让我知道我应该修改或补充哪些部分。
谢谢。
我正在使用带有Spring-boot v2.1.4和Maven构建的eclipse 2019-03。
MovieList.java
package movie;
public class MovieList {
private final long year;
private final String title;
public String getTitle() {
return title;
}
public long getYear() {
return year;
}
public MovieList( long year, String title) {
this.title = title;
this.year = year;
}
}
MovieListController.java
package movie;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MovieListController {
private static final String template = "The movie - %s ( %d )";
@RequestMapping(value="/movielist", method=RequestMethod.GET)
public MovieList movie(
@RequestParam(value="title") String title,
@RequestParam(value="year") long year,
@RequestHeader(value="test") String header
) {
if(title == null) {
throw new MyException("test execution");
} else {
return new MovieList( year, String.format(template, title, year));
}
}
}
包含主要功能的Application.java
package movie;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
MyException.java
package movie;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class MyException extends RuntimeException {
private static final long serialVersionUID = 1L;
public MyException(String msg) {
super(msg);
}
}